【问题标题】:How to Mock a Guzzle Request for PHPUnit如何模拟 PHPUnit 的 Guzzle 请求
【发布时间】:2018-10-12 08:11:46
【问题描述】:

我有这样的课程:

class CategoryClient
{
    private $categories;

    /**
     * Constructor
     * Retrieves JSON File
     */
    public function __construct(Client $client)
    {
        $response = $client->request('GET', config('services.url'));
        $this->categories = collect(json_decode($response->getBody(), true));
    }
}

我将如何模拟 json 响应以在 PHPUnit 中进行测试?并设置$this->categories 变量?

【问题讨论】:

    标签: laravel-5 mocking phpunit


    【解决方案1】:

    您可以使用 Guzzle 测试策略的 Mock Handler 并实例化您的 Client 类。例如:

     $mock = new MockHandler([
                new Response(200, [], '{
                                          "categories": [
                                          { "id" : 1,
                                            "name": "category name 1"},
                                          { "id" : 2,
                                            "name": "category name 3"},
                                            ]
                                            }');
    
    $handler = HandlerStack::create($mock);
    $guzzleClient= new Client(['handler' => $handler]);
    
    $categoryClient = new CategoryClient($guzzleClient);
    

    希望有帮助

    【讨论】:

    • 完美。谢谢:-D
    • 我在嘲笑 guzzle 时接受它 - 它“忽略”任何请求?因此,尽管在构造函数中使用了 $response->getBody() 它仍然能够返回所需的 json
    猜你喜欢
    • 2018-08-07
    • 2020-04-22
    • 2018-05-29
    • 2016-10-06
    • 2018-03-03
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    相关资源
    最近更新 更多