1

私のテストでは、リクエストに合わせてCookieを指定したいと思います。コードをさかのぼって、クライアントの__constructでCookiejarがどのように使用されているかを確認しました。ここの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());
    }
}
4

1 に答える 1

11

コードにエラーがあります:

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

メソッドcreateClientは次のように定義されています(Symfony 2.0.0の場合)。

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

createClientしたがって、メソッドはテストコンテナからクライアントのインスタンスを取得するため、2つのパラメータのみを取り、Cookieの場所はありません。

$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);
于 2012-06-13T14:48:16.400 に答える