【发布时间】:2015-06-19 14:32:27
【问题描述】:
我正在尝试构建一个查询外部 API 的类。对应于端点的每个方法都会调用一个“主调用”方法,该方法负责实际向 API 发送请求。
例如:
// $this->http is Guzzlehttp\Client 5.3
public function call($httpMethod, $endpoint, array $parameters = [])
{
$parameters = array_merge($parameters, [
'headers' => [
'something' => 'something'
]
]);
$request = $this->http->createRequest($httpMethod, $this->baseUrl . $endpoint, $parameters);
return $this->http->send($request);
}
public function getAll()
{
return $this->call('GET', 'all');
}
我应该模拟什么?我应该在 http 客户端的 createRequest() 和 send() 方法上使用 willBeCalled() 和/或 willReturn() 吗?
当我模拟 send() 时,它会说:Argument 1 passed to Double\GuzzleHttp\Client\P2::send() must implement interface GuzzleHttp\Message\RequestInterface, null given
而且我不确定如何为此提供一个假的,因为为该接口创建一个虚拟对象需要我在该类上实现 30 个方法。
这是现在的测试:
function it_lists_all_the_things(HttpClient $http)
{
$this->call('GET', 'all')->willBeCalled();
$http->createRequest()->willBeCalled();
$http->send()->willReturn(['foo' => 'bar']);
$this->getAll()->shouldHaveKeyWithValue('foo', 'bar');
}
【问题讨论】:
标签: unit-testing guzzle phpspec