更新见下文
我的控制器区分ajax和其他请求(Request::ajax()用作条件).这工作得很好,但我想知道是否有一种单元测试控制器处理请求的方法.测试应该如何?这样的事可能但是它不起作用......
<?php
class UsersControllerTest extends TestCase
{
public function testShowUser()
{
$userId = 1;
$response = $this->call('GET', '/users/2/routes', array(), array(), array(
'HTTP_CUSTOM' => array(
'X-Requested-With' => 'XMLHttpRequest'
)
));
}
}
Run Code Online (Sandbox Code Playgroud)
更新
我找到了一个解决方案.也许.由于我对测试Request类的正确功能不感兴趣(很可能Laravel,Symfony等提供的所有本机类已经足够单元测试),最好的方法可能是模拟它的ajax方法.像这样:
public function testShowUser()
{
$mocked = Request::shouldReceive('ajax')
->once()
->andReturn(true);
$controller = new UsersCustomRoutesController;
$controller->show(2,2);
}
Run Code Online (Sandbox Code Playgroud)
因为Request在使用类的call方法时使用真正的类而不是它的模拟替换,Testcase我必须实例化手动输入指定路径时调用的方法.但我认为这是可以的,因为我只想控制Request::ajax()条件内的表达式在此测试中按预期工作.