LoginSignup
0
0
お題は不問!Qiita Engineer Festa 2023で記事投稿!

Laravel PHPUnit Logファサードのモックを作って使う

Posted at

概要

  • リクエスト情報をログに出力するミドルウェアを作成した。そのミドルウェアのUnitテストを記載したい。LogファサードのメソッドをMockeryを使ってモックしてみたので簡単にまとめる。

セオリー

  • モックを定義する際は、当たり前だが、テストでテスト対象のメソッドが実行される前に、テスト対象のメソッド内で実行されるメソッドをモックしておく必要がある。
  • モックする際は「メソッド名」、「引数」、「戻り値」を定義して上げる必要がある。

テストで確認したいコード

  • テストで確認したいコードの一部を下記に記載する。

    Log::channel('request_response_log')->info('Request:', [
        'is_client_ip_unreliable' => $isClientIpUnreliable,
        'client_ip' => $clientIp,
        'method' => $request->method(),
        'url' => $request->fullUrl(),
        'headers' => $request->headers->all(),
        'body' => $request->getContent(),
    ]);
    

テストメソッド

  • 下記にテストメソッドを記載する。

    LogRequestTest.php
    public function test_リクエストのログ出力(): void
    {
        // Log facadeのメソッドをモックで用意
        Log::shouldReceive('channel')
            ->with('request_response_log')
            ->andReturnSelf();
        Log::shouldReceive('info')
            ->withArgs(function ($message, $context) {
                $this->assertSame('Request:', $message);
    
                $this->assertArrayHasKey('is_client_ip_unreliable', $context);
                $this->assertArrayHasKey('client_ip', $context);
                $this->assertArrayHasKey('method', $context);
                $this->assertArrayHasKey('url', $context);
                $this->assertArrayHasKey('headers', $context);
                $this->assertArrayHasKey('body', $context);
    
                return true;
            });
    
        // ミドルウェアを作成
        $middleware = new LogRequestAndResponse();
    
        // リクエストとレスポンスを作成
        $request = new Request();
        $response = new Response();
    
        // ミドルウェアを実行
        $middleware->handle($request, function ($req) use ($response) {
            return $response;
        });
    }
    

Mockeryのメモ

shouldReceiveメソッド(※メソッド名の指定)

  • モックするメソッド名を引数で定義する。

withメソッド(※引数の指定)

  • モックするメソッドの引数を定義する。

withArgs(※引数の指定)

  • モックするメソッドの引数でクロージャを設定したい場合に使う。
  • クロージャがtrueを帰す場合に初めて適用されるので注意する。

andReturnSelfメソッド(※戻り値の指定)

  • 戻り値として自身のオブジェクトを返す。

参考文献

0
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
0
0