0

我是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);
}

失踪。

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

购买请求.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?

4

1 回答 1

0

好的,所以这就是解决方案:

原始问题

我的 PucrhaseResponse.php 中缺少此内容:

use Omnipay\Common\Message\RequestInterface;

//and...

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

购买请求.php:

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

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

解决更新中的404问题

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

购买请求.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());
}
于 2015-01-25T03:11:29.997 回答