LoginSignup
0
1

More than 1 year has passed since last update.

【Laravel】自分で追加したファサードをFeatureテストでモックする方法

Posted at

環境

Laravel 8

結論

以下のマニュアルの通り
デフォルトのファサードと何ら変わらない

以下は/users実行時にCacheファサードを利用する場合の例

Test.php
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function testGetIndex()
    {
        $uri = "/users"
        Cache::shouldReceive('get')
                    ->once()
                    ->with('key')
                    ->andReturn('value');

        $response = $this->getJson(
            $uri,
            [
                'id' => 24,
            ],
            []
        );
        
    }
}

※パラメータなどは適当

/usersをリクエストすると、内部でCacheファサードのget()を実行する想定

  1. shouldReceive()でCacheファサードのget()をモック
  2. getJson()でAPI実行
  3. /usersリクエスト時、内部で実行されるCacheファサードのgetメソッドは'value'を返す

という流れ

外部APIの実行結果をモックする場合も使える

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