我的__constructrt:中有这段代码
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->dbUserService = app()->make('DBUserService');
}
现在,当我进行单元测试时,我知道我可以模拟Guard并将其模拟传递给$auth,但我如何模拟dbUserService
?它是通过IoC容器实例化的。
您可以使用IoC容器的instance()
方法来模拟任何与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;
});