我正在尝试构建一个查询外部API的类。对应于终结点的每个方法都调用负责实际向 API 发送请求的"主调用"方法。
例如:
// $this->http is GuzzlehttpClient 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 DoubleGuzzleHttpClientP2::send() must implement interface GuzzleHttpMessageRequestInterface, 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');
}
你应该嘲笑这种行为,像这样:
public function let(Client $http)
{
$this->beConstructedWith($http, 'http://someurl.com/');
}
function it_calls_api_correctly(Client $http, Request $request)
{
$parameters = array_merge([
'headers' => [
'something' => 'something'
]
]);
$http->createRequest('GET', 'http://someurl.com/all', $parameters)->shouldBeCalled()->willReturn($request);
$http->send($request)->shouldBeCalled();
$this->getAll();
}