php - 如何在php中对curl调用进行单元测试

标签 php curl phpunit

您将如何对 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);
  }

我需要测试返回的内容类型,以便它可以抛出异常。

最佳答案

按照 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);
    }
}

现在您可以使用 HttpRequest 接口(interface)的模拟进行测试,而无需调用任何 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();
}

编辑修正简单的 PHP 解析错误。

关于php - 如何在php中对curl调用进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7911535/

相关文章:

php - 测试用户是否登录 laravel 5.7

php - 找不到 PHPUnit 类 'mysqli'

php - 在 PHP 中解析 XML 提要

java - 使用 Java 的 POST 请求(AsyncTask)

curl - Linuxbrew curl 证书问题

php - libcurl 不支持或禁用协议(protocol) https

php - 如何在 PHPUnit 中 stub 更复杂的方法

php - Laravel API 从速率限制中排除 1 个 IP 地址

php - PHP 中类型提示的性能开销是多少?

php - 包括其中包含函数的 PHP 文件是否会减慢包含那些即使不被使用的页面?