3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GuzzleHttpでのレスポンスをモック化してテストする

Last updated at Posted at 2020-08-11

まえがき

GuzzleHttpを利用してHTTPリクエストをしている処理のユニットテストを書きたい。
GuzzleHttpにはレスポンスをモック化する機能が用意されているようなので、こちらを利用してみることにします。

実装例

HogeTest.php
<?php

use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Client;

class HogeTest extends \Codeception\Test\Unit
{
    /**
     * @group guzzletest
     */
    public function testGuzzleTest()
    {
        /* Arrange */
        $response = new Response(200, [], 'Response Body');
        $mock = new MockHandler([$response]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);

        $url = 'http://localhost:8080/';
        $params = [
            'token' => 'hogehoge'
        ];

        /* Act */
        $res = $client->post($url, ['form_params' => $params]);

        /* Assert */
        $this->assertEquals('Response Body', $res->getBody());
    }
}
実行結果
$ vendor/bin/codecept run unit --group guzzletest -c common/
Codeception PHP Testing Framework v3.0.2
Powered by PHPUnit 8.2.4 by Sebastian Bergmann and contributors.
Running with seed: 

[Groups] guzzletest 

Common\tests.unit Tests (1) -----------------------------------------------------------
✔ HogeTest: Guzzle test (0.04s)
---------------------------------------------------------------------------------------


Time: 1.96 seconds, Memory: 32.00 MB

OK (1 test, 1 assertion)
  • 上記例では、テストコードで直接クライアントを作成している
  • GuzzleHttpを利用しているServiceクラスやcomponentのテストを行う場合、setClient()などを実装していれば、MockHandlerで生成したClientをテストコードからセットしてレスポンスをモック化する

つまりGuzzleはとても便利。。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?