在没有API的情况下如何测试客户端?

时间:2019-08-09 20:35:36

标签: php http mocking phpunit phpunit-testing

我决定编写一个向HTTP发送HTTP请求的客户端。有3种类型的请求:GET,POST,PUT。我们需要使用phpunit编写单元测试,这将使我们无需编写API即可测试功能。我的第一个想法是使用模拟对象。阅读了足够的文献后,我无法理解该怎么做。据我了解,无论我去到哪里,都需要为API创建一个存根。请告诉我朝哪个方向移动以解决问题。

<?php

namespace Client;

class CurlClient implements iClient
{
    private $domain;

    public function __construct($domain = "http://example.com")
    {
        $this->domain = $domain;
    }

    public function getAllComments()
    {
        $ch = curl_init($this->domain.'/comments');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $comments = curl_exec($ch);

        $comments = json_decode($comments);

        curl_close($ch);

        return $comments;
    }

    public function addNewComment($data)
    {
        $ch = curl_init($this->domain.'/comment');

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_exec($ch);

        $statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

        $statusCode = (string)$statusCode;
        $statusCode = (int)$statusCode[0];

        curl_close($ch);

        return $statusCode == 2 ? true : false;
    }

    public function updateComment($id, $data)
    {
        $ch = curl_init($this->domain.'/comment/'.$id);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_exec($ch);

        $statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

        $statusCode = (string)$statusCode;
        $statusCode = (int)$statusCode[0];

        curl_close($ch);

        return $statusCode == 2 ? true : false;
    }
}

1 个答案:

答案 0 :(得分:0)

这是一个使用phpunit的简单模拟示例。 phpunit的模拟功能是广泛的,有关更多信息,phpunit documentation - test doubles

<?php
use PHPUnit\Framework\TestCase;

  // Use the getMockBuilder() method that is provided by the   
  // PHPUnit\Framework\TestCase class to set up a mock object
  //  for the CurlClient object.

class CurlClientTest extends TestCase
{
    public function testAddNewComment()
    {
        // Create a mock for the CurlClient class,
        // only mock the update() method.
        $client = $this->getMockBuilder(CurlClient::class)
                         ->setMethods(['addNewComment'])
                         ->getMock();
        $map = [
          ['hello', true],
          [123, false]
        ];

        $client->method('addNewComment')->will($this->returnValueMap($map));

        $this->assertEquals(true, $client->addNewComment('hello'));
        $this->assertEquals(false, $client->addNewComment(123));
    }
}