我正在尝试构建一个查询外部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客户端willBeCalled()
和willReturn()
方法上使用createRequest()
和/或send()
吗?
当我模仿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');
}
答案 0 :(得分:1)
你应该嘲笑这种行为,如下所示:
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();
}