I am using PHPUnit and Guzzle to make API unit test. The probleme I have is that I am not able or I can't really figure out how to persiste cookie between my test methods. Or maybe am doing it all wrong ^^
The first test testGetFirst
gets the data and set a session cookie on server side. The response has a Set-Cookie
header with the right cookie.
The seconde test testGetSecond
should return a data set if the cookie exists. Unfortunatelly it seems that Guzzle::Client
doesn't store/persiste the cookie between the methods.
use PHPUnit\Framework\TestCase;
use GuzzleHttp\Client;
class MyTest extends Testcase
{
public $guzzleClient;
/**
* @before
*/
function initVariables() {
$this->guzzleClient = new Client([
'base_uri' => 'http://apiuri.com',
'cookies' => true
]);
}
// This call get some data and set a cookie (session cookie) on server side
function testGetFirst() {
$params = [
'query' => [
'param1' => 'myparam'
]
];
$response = $this->guzzleClient->request('GET', '/', $params);
// if I print out the response headers I get my cookie in 'Set-Cookie' header
// I suppose the cookie has been set correctly
print_r($response->getHeaders());
// if I print out the client conf cookie, I get the cookie too
print_r($this->guzzleClient->getConfig('cookies')->toArray());
}
// This call get data to have access it need to use a cookie that has been set by testGetFirst
// But unfortunatelly the cookie is empty while making the request
/**
* @depends testGetFirst
*/
function testGetSecond() {
$params = [
'query' => [
'param1' => 'hello'
]
];
// if I print out the client conf cookie, cookies is empty
print_r($this->guzzleClient->getConfig('cookies')->toArray());
$response = $this->guzzleClient->request('GET', '/second', $params);
// as the request can't access to a cookie it sends an error response
}
}
I know there is CookieJar
that I can use in each method and pass the Set-Cookie
value in to Jar
but I was hopping to avoid it.
Do you have any idea or suggestion ?
Very appreciate your help.