Laravel 5.6模拟Guzzle响应

问题描述 投票:0回答:1

我试图嘲笑特定api的guzzle响应。

我的控制器代码看起来像这样(为简洁起见):

class SomeClass
{

    private $guzzle;

    public function __construct(\GuzzleHttp\Client $guzzle) {
        $this->guzzle = new $guzzle();
    }

    public function makeRequest(){

        $client = $this->guzzle;

        $url = 'http//somerurl';
        $options = [];

        $response = $client->request('POST', $url, $options);    

        return $response;
    }
}

测试看起来像这样(再次编辑)......

public function someTest(){

     $mock = $this->createMock(\GuzzleHttp\Client::class);

     $mock->method('request')->willReturn([
         'response' => 'somedata'
     ]);

     $someClass = new $SomeClass($mock);

     $response = $someClass->makeRequest();

     $body = $response->getBody();

     ...
}

此时测试返回“调用成员函数getBody on null”;

如何测试一个guzzle call的getBody响应?

先感谢您...

laravel-5 phpunit guzzle6
1个回答
1
投票

使用Guzzle进行测试的一种方法是配置MockHandler

http://docs.guzzlephp.org/en/stable/testing.html

因此,不要嘲笑guzzle客户端,而是创建一个这样的:

public function someTest() {

    $mock = new MockHandler([
        new Response(200, [], 'The body!'),
        // Add more responses for each response you need
    ]);

    $handler = HandlerStack::create($mock);
    $client = new Client(['handler' => $handler]);

    $someClass = new SomeClass($client);

    $response = $someClass->makeRequest();

    $body = $response->getBody();

    $this->assertSame('The body!', $body);
}
© www.soinside.com 2019 - 2024. All rights reserved.