更新见下文
我的控制器区分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()条件内的表达式在此测试中按预期工作.
And*_*eas 15
您需要在实际标头前加上HTTP_,不需要使用HTTP_CUSTOM:
$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$this->call('get', '/ajax-route', array(), array(), $server);
Run Code Online (Sandbox Code Playgroud)
替代语法看起来好一点IMO:
$this->client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest');
$this->call('get', '/ajax-route');
Run Code Online (Sandbox Code Playgroud)
以下是JSON标头(Request::isJson()和Request::wantsJson())的一些类似代码示例:
$this->client->setServerParameter('HTTP_CONTENT_TYPE', 'application/json');
$this->call('get', '/is-json');
$this->client->setServerParameter('HTTP_ACCEPT', 'application/json');
$this->call('get', '/wants-json');
Run Code Online (Sandbox Code Playgroud)
这是一个有用的辅助方法,可以放在TestCase中:
protected function prepareAjaxJsonRequest()
{
$this->client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest');
$this->client->setServerParameter('HTTP_CONTENT_TYPE', 'application/json');
$this->client->setServerParameter('HTTP_ACCEPT', 'application/json');
}
Run Code Online (Sandbox Code Playgroud)
这是Laravel 5.2的解决方案.
$this->json('get', '/users/2/routes');
Run Code Online (Sandbox Code Playgroud)
就这么简单.
最初,json方法适用于以下标题:
'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
'CONTENT_TYPE' => 'application/json',
'Accept' => 'application/json',
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5237 次 |
| 最近记录: |