我决定编写一个向 API 发送 http 请求的客户端。有 3 种类型的请求:GET、POST、PUT。我们需要使用 phpunit 编写单元测试,这将允许我们在不编写 API 的情况下测试功能。我的第一个想法是使用模拟对象。阅读了足够多的文献后,我无法以任何方式理解如何做到这一点。据我了解,无论我的请求在哪里,我都需要为 API 创建一个 stub 。请告诉我朝哪个方向移动以解决问题。
<?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;
}
}
最佳答案
这是一个使用 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));
}
}
关于php - 在没有API的情况下如何测试客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57436810/