您如何进行单元测试curl实现?
public function get() {
$ch = curl_init($this->request->getUrl());
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
if (!strstr($type, 'application/json')) {
throw new HttpResponseException('JSON response not found');
}
return new HttpResponse($code, $result);
}
Run Code Online (Sandbox Code Playgroud)
我需要测试返回的内容类型,以便它可以抛出异常.
Dav*_*ess 52
正如thomasrutter建议的那样,创建一个类来抽象cURL函数的用法.
interface HttpRequest
{
public function setOption($name, $value);
public function execute();
public function getInfo($name);
public function close();
}
class CurlRequest implements HttpRequest
{
private $handle = null;
public function __construct($url) {
$this->handle = curl_init($url);
}
public function setOption($name, $value) {
curl_setopt($this->handle, $name, $value);
}
public function execute() {
return curl_exec($this->handle);
}
public function getInfo($name) {
return curl_getinfo($this->handle, $name);
}
public function close() {
curl_close($this->handle);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用HttpRequest接口的模拟进行测试,而无需调用任何cURL函数.
public function testGetThrowsWhenContentTypeIsNotJson() {
$http = $this->getMock('HttpRequest');
$http->expects($this->any())
->method('getInfo')
->will($this->returnValue('not JSON'));
$this->setExpectedException('HttpResponseException');
// create class under test using $http instead of a real CurlRequest
$fixture = new ClassUnderTest($http);
$fixture->get();
}
Run Code Online (Sandbox Code Playgroud)
编辑修复了简单的PHP解析错误.
您可以使用函数模拟库。我为你做了一个:php-mock-phpunit
namespace foo;
use phpmock\phpunit\PHPMock;
class BuiltinTest extends \PHPUnit_Framework_TestCase
{
use PHPMock;
public function testCurl()
{
$curl_exec = $this->getFunctionMock(__NAMESPACE__, "curl_exec");
$curl_exec->expects($this->once())->willReturn("body");
$ch = curl_init();
$this->assertEquals("body", curl_exec($ch));
}
}
Run Code Online (Sandbox Code Playgroud)