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

时间:2015-03-30 14:46:59

标签: php unit-testing laravel phpunit

我在__construrct中有这段代码:

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

现在,当我进行单元测试时,我知道我可以模仿Guard并将其模拟为$ auth,但我怎么能模仿dbUserService?它通过IoC容器实例化。

1 个答案:

答案 0 :(得分:1)

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

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