在涉及 Guzzle 的 phpspec 中测试 class

Testing a class in phpspec involving Guzzle

我正在尝试构建一个查询外部 API 的 class。对应于端点的每个方法都会调用 'master call' 方法,该方法负责实际向 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() and/or willReturn() 吗?

当我模拟 send() 时,它说:Argument 1 passed to Double\GuzzleHttp\Client\P2::send() must implement interface GuzzleHttp\Message\RequestInterface, null given 而且我不确定如何为此提供伪造,因为为该接口创建虚拟对象需要我在该 class.

上实现 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();
}