【发布时间】:2015-11-12 22:59:56
【问题描述】:
我正在尝试为 ajax 端点编写一些 PHPUnit 测试。当用户不必登录时,我可以毫不费力地做到这一点。但要测试有问题的端点,用户必须登录,并且我想以编程方式获取 cookie 作为测试的一部分。基本上我想运行的测试看起来像:
$url = "https://example.com/ajax/endpoint";
$fields = array(
'name'=>'test '.rand(),
'host'=>rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255),
'port'=>rand(1,1000)
);
$fields_string = "";
foreach ($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string, '&');
ob_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_COOKIE, $userCookie);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
$this->assertEquals(true, $response);
$json = ob_get_contents();
$return = json_decode($json);
$this->assertEquals('false', $return->success);
$this->assertEquals('', $return->data);
ob_end_clean();
但除了打开浏览器,登录,然后从浏览器中的 cookie 中读取 PHPSESSID 之外,我不知道获得$userCookie 的好方法。如何在不手动抓取的情况下获取 cookie?我希望能够从 curl 请求到登录端点获取它:
$url = "https://example.com/ajax/login";
$fields = array(
'username'=>$username,
'password'=>$password
);
$fields_string = "";
foreach ($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
【问题讨论】:
-
我手头的问题没有解决方案。但是当我在同一个句子中看到 unittest ajax call 这个词时,我开始怀疑了。单元测试不应访问网络/IO 或任何其他系统板。尝试模拟网络访问或在集成测试中进行测试。
-
你应该添加 curl 标签。此外,就像@lukassteiner 所说,这确实是一个集成测试,因为您既依赖于网络/IO 和会话/登录。
标签: php session cookies phpunit session-cookies