首先,我知道了 文档 状态:
注意:您不应该模拟请求外观。相反,在运行测试时,将您想要的输入传递给HTTP帮助程序方法,例如调用和发布。
但 那种测试更像是 整合或功能 因为即使你正在测试一个 调节器 (该 SUT
),你没有将它与它的依赖性脱钩(Request
和其他人,稍后更多关于这一点)。
所以我正在做的,为了做正确的事 TDD
循环,嘲笑 Repository
, Response
和 Request
(我有问题)。
我的测试看起来像这样:
public function test__it_shows_a_list_of_categories() {
$categories = [];
$this->repositoryMock->shouldReceive('getAll')
->withNoArgs()
->once()
->andReturn($categories);
Response::shouldReceive('view')
->once()
->with('categories.admin.index')
->andReturnSelf();
Response::shouldReceive('with')
->once()
->with('categories', $categories)
->andReturnSelf();
$this->sut->index();
// Assertions as mock expectations
}
这完全正常,他们遵循 安排,行动,断言 样式。
问题在于 Request
,如下所示:
public function test__it_stores_a_category() {
Redirect::shouldReceive('route')
->once()
->with('categories.admin.index')
->andReturnSelf();
Request::shouldReceive('only')
->once()
->with('name')
->andReturn(['name' => 'foo']);
$this->repositoryMock->shouldReceive('create')
->once()
->with(['name' => 'foo']);
// Laravel facades wont expose Mockery#getMock() so this is a hackz
// in order to pass mocked dependency to the controller's method
$this->sut->store(Request::getFacadeRoot());
// Assertions as mock expectations
}
你可以看到我嘲笑了 Request::only('name')
呼叫。但是当我跑步的时候 $ phpunit
我收到以下错误:
BadMethodCallException: Method Mockery_3_Illuminate_Http_Request::setUserResolver() does not exist on this mock object
因为我不直接打电话 setUserResolver()
从我的控制器,这意味着它是由执行直接调用 Request
。但为什么?我模拟了方法调用,它不应该调用任何依赖。
我在这里做错了什么,为什么我收到此错误消息?
PS:作为奖励,我通过在Laravel框架上使用单元测试强制TDD来查看它是错误的方式,因为它似乎通过耦合依赖关系和SUT之间的交互来进行集成测试。 $this->call()
?