Laravel Mockery - 模拟一个具有注入构造函数的依赖项的类


Laravel Mockery - Mocking a class with dependencies injected into constructor

我试图用它自己的构造函数依赖项来模拟一个类。我正在使用Laravel 5.2。

class A {
    public function something() {}
}    
class B {
  protected $a;
  public function __construct(A $a) {
    $this->a = $a;
  }
  public function getA() {
    return $this->a->something();
  }
}
MockingTest extends TestCase {
  public function testItGetsSomething() {
    $m = Mockery::mock('B');
    $m->shouldReceive('getA')->once()->andReturn('Something');
  }
}

我知道我可以将ClassB.__construct(A $a)更改为:

  public function __construct(A $a = null) {
    $this->a = $a ?: new A();
  }

但是有没有更好/更清洁的方法呢?如果有更可接受的方法,我不想仅仅为了单元测试而更改我的构造函数代码。

我不是 100% 确定您要测试什么,但是如果您想在 B 类中模拟类 A 实例,您可以在创建 B 的新实例时注入 A 的模拟版本:

$mockA = Mockery::mock('A');
$mockA->shouldReceive('something')->once()->andReturn('Something');
$classBwithMockedA = new B($mockA);

然后你可以这样做(如果你想在B类中测试getA方法):

$this->assertEquals('Something', $classBwithMockedA->getA());