Omnipay PHPUnit Guzzle httpClient 404 错误 - 模拟 json

Omnipay PHPUnit Guzzle httpClient 404 Error - mock json

我是 OmniPay 的新手,正在试用它并尝试制作一个简单的自定义网关,并使用模拟 json http 响应创建单元测试。

在 GatewayTest.php 中我设置了模拟 http 响应:

public function testPurchaseSuccess()
{
    $this->setMockHttpResponse('TransactionSuccess.txt');

    $response = $this->gateway->purchase($this->options)->send();

    echo $response->isSuccessful();

    $this->assertEquals(true, $response->isSuccessful());
}

在 PurchaseRequest.php 中,我正在尝试以某种方式获取它:

public function sendData($data)
{
    $httpResponse = //how do I get the mock http response set before?

    return $this->response = new PurchaseResponse($this, $httpResponse->json());
}

那么如何在 PurchaseRequest.php 中获取模拟 http 响应?

---更新---

原来在我的PurchaseResponse.php

use Omnipay\Common\Message\RequestInterface;

//and...

public function __construct(RequestInterface $request, $data)
{
    parent::__construct($request, $data);
}

失踪了。

现在 PurchaseRequest.php 中的 $httpResponse = $this->httpClient->post(null)->send(); 断言是可以的,但是当我使用 httpClient 时,Guzzle 会抛出 404 错误。我检查了 Guzzle's docs 并尝试创建一个模拟响应,但是我的断言再次失败并且 404 仍然存在:

PurchaseRequest.php

public function sendData($data)
{
    $plugin = new Guzzle\Plugin\Mock\MockPlugin();
    $plugin->addResponse(new Guzzle\Http\Message\Response(200));

    $this->httpClient->addSubscriber($plugin);

    $httpResponse = $this->httpClient->post(null)->send(); 

    return $this->response = new PurchaseResponse($this, $httpResponse->json());

}

有什么建议,如何摆脱 404?

好的,这就是最终的解决方案:

原题

我的 PucrhaseResponse.php 中缺少这个:

use Omnipay\Common\Message\RequestInterface;

//and...

public function __construct(RequestInterface $request, $data)
{
    parent::__construct($request, $data);
}

PurchaseRequest.php:

public function sendData($data)
{
    $httpResponse = $this->httpClient->post(null)->send();

    return $this->response = new PurchaseResponse($this, $httpResponse->json());
}

解决更新中的404问题

为了防止 Guzzle 抛出异常,我不得不为 request.error 添加一个侦听器。

PurchaseRequest.php:

public function sendData($data)
{
    $this->httpClient->getEventDispatcher()->addListener(
        'request.error',
        function (\Guzzle\Common\Event $event) {
            $event->stopPropagation();
        }
    );

    $httpResponse = $this->httpClient->post(null)->send(); 

    return $this->response = new PurchaseResponse($this, $httpResponse->json());
}