【发布时间】:2018-12-19 08:22:34
【问题描述】:
我正在使用 PHPUnit 和 Guzzle 进行 API 单元测试。我遇到的问题是我无法或我无法真正弄清楚如何在我的测试方法之间保留 cookie。或者也许我做错了^^
第一个测试testGetFirst 获取数据并在服务器端设置会话cookie。响应有一个带有正确 cookie 的 Set-Cookie 标头。
如果 cookie 存在,第二个测试 testGetSecond 应该返回一个数据集。不幸的是,Guzzle::Client 似乎没有在方法之间存储/持久化 cookie。
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
}
}
我知道我可以在每种方法中使用 CookieJar 并将 Set-Cookie 值传递给 Jar 但我想避免它。
您有什么想法或建议吗?
非常感谢您的帮助。
【问题讨论】:
标签: php cookies phpunit session-cookies guzzle