jvr*_*rnt 3 php phpunit unit-testing laravel
我的 __constructurct 中有这段代码:
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->dbUserService = app()->make('DBUserService');
}
Run Code Online (Sandbox Code Playgroud)
现在,当我进行单元测试时,我知道我可以模拟 Guard 并将其模拟传递给 $auth,但我如何模拟dbUserService?它是通过 IoC 容器实例化的。
您可以使用instance()IoC 容器的方法来模拟任何实例化的类make():
$mock = Mockery::mock(); // doesn't really matter from where you get the mock
// ...
$this->app->instance('DBUserService', $mock);
Run Code Online (Sandbox Code Playgroud)
如果您需要使用上下文绑定来模拟实例,例如:
app()->make(MyClass::class, ['id' => 10]);
Run Code Online (Sandbox Code Playgroud)
您可以使用bind代替instance:
$mock = Mockery::mock(MyClass::class, function($mock) {
$mock->shouldReceive('yourMethod')->once();
})
$this->app->bind(MyClass::class, function() use($mock) {
return $mock;
});
Run Code Online (Sandbox Code Playgroud)