【发布时间】:2015-10-21 15:52:02
【问题描述】:
在我的 Laravel 应用程序中,我有一个控制器,它具有显示特定资源的方法。例如。说 url 是 /widgets/26 我的控制器方法可能像这样工作:
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
}
【问题讨论】:
标签: php unit-testing laravel phpunit