In my test, I’d like to specify a cookie to go along with the request. I traced the code back to see how a cookie jar is used in the Client’s __construct. Though a var_dump here and a var_dump on the server side show no cookie being sent with the request. I also tried sending a simpler string with HTTP_COOKIE as shown.
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());
}
}
You have an error in code:
Method
createClientis defined as following (for Symfony 2.0.0):So, it takes only two parameters and there is no place for cookie, because
createClientmethod takes an instance of client from the test container:Here is a definition for the
test.clientservice:Now we see, that cookie jar service is injected into
test.clientand have a scopeprototypewhich means that new object will be created on each access to that service.However
Clientclass has a methodgetCookieJar()and you can use it to set specific cookies for request (not tested, but expected to work):