在我的测试中,我想指定一个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());
}
}
Run Code Online (Sandbox Code Playgroud)
lis*_*nko 11
您的代码有错误:
$client = static::createClient(array(), array(), $jar); // Third parameter ?
Run Code Online (Sandbox Code Playgroud)
方法createClient定义如下(对于Symfony 2.0.0):
static protected function createClient(array $options = array(), array $server = array())
Run Code Online (Sandbox Code Playgroud)
因此,它只需要两个参数,并且没有cookie的位置,因为createClient方法从测试容器中获取客户端的实例:
$client = static::$kernel->getContainer()->get('test.client');
$client->setServerParameters($server);
return $client;
Run Code Online (Sandbox Code Playgroud)
以下是该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" />
Run Code Online (Sandbox Code Playgroud)
现在我们看到,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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5001 次 |
| 最近记录: |