【发布时间】:2019-12-17 14:15:39
【问题描述】:
我决定编写一个向 API 发送 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;
}
}
【问题讨论】: