在我的 Laravel 应用程序中,我有一个带有显示特定资源方法的 Controller 。例如。假设 url 是 /widgets/26
我的 Controller 方法可能会像这样工作:
Class WidgetsController {
protected $widgets;
public function __construct(WidgetsRepository $widgets)
{
$this->widgets = $widgets;
}
public function show($id)
{
$widget = $this->widgets->find($id);
return view('widgets.show')->with(compact('widget'));
}
}
正如我们所见,我的 WidgetsController
有一个 WidgetsRepository
依赖项。在 show
方法的单元测试中,我如何模拟这种依赖关系,以便我实际上不必调用存储库,而只需返回一个硬编码的 widget
?
单元测试开始:
function test_it_shows_a_single_widget()
{
// how can I tell the WidgetsController to be instaniated with a mocked WidgetRepository?
$response = $this->action('GET', 'WidgetsController@show', ['id' => 1]);
// somehow mock the call to the repository's `find()` method and give a hard-coded return value
// continue with assertions
}
最佳答案
您可以模拟存储库类并将其加载到 IoC 容器中。
所以当 Laravel 到达你的 Controller 时,它会发现它已经在那里并且会解析你的模拟而不是实例化一个新的。
function test_it_shows_a_single_widget()
{
// mock the repository
$repository = Mockery::mock(WidgetRepository::class);
$repository->shouldReceive('find')
->with(1)
->once()
->andReturn(new Widget([]));
// load the mock into the IoC container
$this->app->instance(WidgetRepository::class, $repository);
// when making your call, your controller will use your mock
$response = $this->action('GET', 'WidgetsController@show', ['id' => 1]);
// continue with assertions
// ...
}
类似的设置已经过测试,在 Laravel 5.3.21 中运行良好。
关于php - 模拟 Laravel Controller 依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31721238/