symfony2测试用例请求cookie

时间:2012-06-02 02:19:18

标签: symfony phpunit

在我的测试中,我想指定一个cookie来处理请求。我追溯了代码,看看如何在客户端的__construct中使用cookie jar。虽然此处的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());
    }
}

1 个答案:

答案 0 :(得分:10)

代码中有错误:

$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);
相关问题