【问题标题】:symfony2 test case request cookiesymfony2 测试用例请求 cookie
【发布时间】:2012-06-13 22:48:16
【问题描述】:

在我的测试中,我想指定一个 cookie 来配合请求。我追溯了代码以查看 cookie jar 是如何在客户端的 __construct 中使用的。尽管此处的 var_dump 和服务器端的 var_dump 显示没有 cookie 随请求一起发送。我还尝试使用 HTTP_COOKIE 发送一个更简单的字符串,如图所示。

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\BrowserKit\CookieJar;
class DefaultControllerTest extends WebTestCase {
    public function test() {
        $jar = new CookieJar();
        $cookie = new Cookie('locale2', 'fr', time() + 3600 * 24 * 7, '/', null, false, false);
        $jar->set($cookie);
        $client = static::createClient(array(), array(), $jar);  //this doesn't seem to attach cookies as expected!
        $crawler = $client->request(
            'GET', //method
            '/', //uri
            array(), //parameters
            array(), //files
            array(
                'HTTP_ACCEPT_LANGUAGE' => 'en_US',
                //'HTTP_COOKIE' => 'locale2=fr' //this doesn't work either!
            ) //server
        );

        var_dump($client->getRequest());
    }
}

【问题讨论】:

  • 您是否尝试过使用$this->get('request'); 创建类似here 的对象或创建类似$response = new RedirectResponse($url); $response->headers->setCookie(new Cookie(... 的对象?

标签: symfony phpunit


【解决方案1】:

你的代码有错误:

$client = static::createClient(array(), array(), $jar); // Third parameter ?

方法createClient定义如下(Symfony 2.0.0):

static protected function createClient(array $options = array(), array $server = array())

所以,它只需要两个参数并且没有cookie的位置,因为createClient方法从测试容器中获取了一个客户端实例:

$client = static::$kernel->getContainer()->get('test.client');
$client->setServerParameters($server);

return $client;

这是test.client 服务的定义:

<service id="test.client" class="%test.client.class%" scope="prototype">
    <argument type="service" id="kernel" />
    <argument>%test.client.parameters%</argument>
    <argument type="service" id="test.client.history" />
    <argument type="service" id="test.client.cookiejar" />
</service>

<service id="test.client.cookiejar" class="%test.client.cookiejar.class%" scope="prototype" />

现在我们看到,cookie jar 服务被注入到test.client 并具有prototype 范围,这意味着将在每次访问该服务时创建新对象。

但是Client 类有一个方法getCookieJar(),您可以使用它为请求设置特定的cookie(未经测试,但预计可以工作):

$client = static::createClient();
$cookie = new Cookie('locale2', 'fr', time() + 3600 * 24 * 7, '/', null, false, false);
$client->getCookieJar()->set($cookie);

【讨论】:

  • 一个完整的解释!最后一个代码块就像一个魅力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
相关资源
最近更新 更多