使用 app()->make 创建的模拟 类

Mocking classes that created with app()->make

我的 __construrct 中有此代码:

public function __construct(Guard $auth)
{
    $this->auth = $auth;
    $this->dbUserService = app()->make('DBUserService');
}

现在,当我进行单元测试时,我知道我可以模拟 Guard 并将其模拟传递给 $auth,但我如何模拟 dbUserService?它是通过 IoC 容器实例化的。

您可以使用 IoC 容器的 instance() 方法来模拟任何 class 实例化 make():

$mock = Mockery::mock(); // doesn't really matter from where you get the mock
// ...
$this->app->instance('DBUserService', $mock);

如果您需要模拟具有上下文绑定的实例,例如:

app()->make(MyClass::class, ['id' => 10]);

您可以使用 bind 而不是 instance:

$mock = Mockery::mock(MyClass::class, function($mock) {
   $mock->shouldReceive('yourMethod')->once();
})

$this->app->bind(MyClass::class, function() use($mock) {
   return $mock;
});