laravel - 如何在 Laravel 测试用例中模拟 xmlHttpRequests?

标签 laravel laravel-4

更新见下文

我的 Controller 区分 ajax 和其他请求(使用 Request::ajax() 作为条件)。这工作得很好,但我想知道是否有一种方法可以对处理请求的 Controller 进行单元测试。测试应该是什么样的? 可能是这样的,但它不起作用......

<?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'
                    )
                ));


            }
        }

更新

我找到了一个解决方案。或许。由于我对测试 Request 类的正确功能不感兴趣(很可能 Laravel、Symfony 等提供的所有 native 类都已经进行了足够的单元测试),最好的方法可能是模拟其 ajax 方法。像这样:

        public function testShowUser()
        {

            $mocked = Request::shouldReceive('ajax')
                ->once()
                ->andReturn(true);
            $controller = new UsersCustomRoutesController;
            $controller->show(2,2);
        }

因为在使用 Testcase 类的 call 方法时使用的是真正的 Request 类,而不是它的模拟替代品,所以我必须实例化手动输入指定路线时调用的方法。但我认为这没关系,因为我只想控制 Request::ajax() 条件内的表达式在此测试中按预期工作。

最佳答案

您需要在实际 header 前添加 HTTP_ 前缀,无需使用 HTTP_CUSTOM:

$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$this->call('get', '/ajax-route', array(), array(), $server);

在我看来,替代语法看起来更好一点:

$this->client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest');
$this->call('get', '/ajax-route');

以下是 JSON header 的一些类似代码示例(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');

这是一个有用的帮助方法,您可以将其放入测试用例中:

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');
}

关于laravel - 如何在 Laravel 测试用例中模拟 xmlHttpRequests?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20093897/

相关文章:

php - Laravel 4 数据库配置 $_ENV

php - 如何限制 Laravel 中的通知数量

php - 谷歌在laravel中绘制标题中的字符重音

php - Laravel 实例错误

javascript - piwik 无法在 HTTPS 中工作

Laravel 4 : which events does it support/have?

php - 使用 JWT-Auth 进行 Laravel 测试

php - Laravel 4 验证说找不到列

php - 在 Laravel 中应用 Eloquent 的 ORM 的最佳方式?

laravel-4 - Laravel whereRaw 带参数不起作用?