【问题标题】:Omnipay PHPUnit Guzzle httpClient 404 Error - mock jsonOmnipay PHPUnit Guzzle httpClient 404 错误 - 模拟 json
【发布时间】:2015-03-23 05:18:03
【问题描述】:

我是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?

【问题讨论】:

    标签: php unit-testing phpunit guzzle omnipay


    【解决方案1】:

    好的,这就是解决方案:

    原来的问题

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

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2016-07-02
      • 2018-02-04
      • 2016-10-08
      相关资源
      最近更新 更多