【问题标题】:Laravel Mockery - Mocking a class with dependencies injected into constructorLaravel Mockery - 模拟一个将依赖项注入构造函数的类
【发布时间】:2016-04-22 03:09:07
【问题描述】:

我正在尝试使用它自己的构造函数依赖项来模拟一个类。我正在使用 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();
  }

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

【问题讨论】:

    标签: php laravel mocking phpunit mockery


    【解决方案1】:

    我不能 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());
    

    【讨论】:

      猜你喜欢
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 2019-04-20
      • 2011-02-02
      • 2013-07-10
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多