モック
はじめに
Laravelアプリケーションのテスト時、特定のテスト中に実際に実行されないように、アプリケーションの特定の側面を「モック」したい場合があります。たとえば、イベントをディスパッチするコントローラーをテストする場合、テスト中に実際には実行されないように、イベントリスナーをモックしたい場合があります。これにより、イベントリスナーは独自のテストケースでテストできるため、イベントリスナーの実行を気にせずに、コントローラーのHTTPレスポンスのみをテストできます。
Laravelは、イベント、ジョブ、その他のファサードをすぐにモックするための便利なメソッドを提供します。これらのヘルパーは主にMockeryの上に便利なレイヤーを提供するため、複雑なMockeryメソッド呼び出しを手動で行う必要はありません。
オブジェクトのモック
Laravelのサービスコンテナを介してアプリケーションに注入されるオブジェクトをモックする場合、モックされたインスタンスをコンテナにinstance
バインディングとしてバインドする必要があります。これにより、コンテナはオブジェクト自体を構築する代わりに、オブジェクトのモックされたインスタンスを使用するように指示されます。
use App\Service;use Mockery;use Mockery\MockInterface; test('something can be mocked', function () { $this->instance( Service::class, Mockery::mock(Service::class, function (MockInterface $mock) { $mock->shouldReceive('process')->once(); }) );});
use App\Service;use Mockery;use Mockery\MockInterface; public function test_something_can_be_mocked(): void{ $this->instance( Service::class, Mockery::mock(Service::class, function (MockInterface $mock) { $mock->shouldReceive('process')->once(); }) );}
これをより便利にするために、Laravelのベーステストケースクラスで提供されるmock
メソッドを使用できます。たとえば、次の例は上記の例と同等です。
use App\Service;use Mockery\MockInterface; $mock = $this->mock(Service::class, function (MockInterface $mock) { $mock->shouldReceive('process')->once();});
オブジェクトの一部のメソッドのみをモックする必要がある場合は、partialMock
メソッドを使用できます。モックされていないメソッドは、呼び出されたときに正常に実行されます。
use App\Service;use Mockery\MockInterface; $mock = $this->partialMock(Service::class, function (MockInterface $mock) { $mock->shouldReceive('process')->once();});
同様に、オブジェクトをスパイしたい場合、Laravelのベーステストケースクラスは、Mockery::spy
メソッドの便利なラッパーとしてspy
メソッドを提供します。スパイはモックに似ています。ただし、スパイはスパイとテスト対象のコード間の相互作用を記録し、コードの実行後にアサーションを行うことができます。
use App\Service; $spy = $this->spy(Service::class); // ... $spy->shouldHaveReceived('process');
ファサードのモック
従来の静的メソッド呼び出しとは異なり、ファサード(リアルタイムファサードを含む)はモックできます。これは、従来の静的メソッドよりも大きな利点を提供し、従来の方法の依存性注入を使用している場合と同じテストのしやすさを実現します。テスト時、コントローラーの1つで発生するLaravelファサードへの呼び出しをモックすることがよくあります。たとえば、次のコントローラーアクションを考えてみましょう。
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Cache; class UserController extends Controller{ /** * Retrieve a list of all users of the application. */ public function index(): array { $value = Cache::get('key'); return [ // ... ]; }}
Mockeryモックのインスタンスを返すshouldReceive
メソッドを使用して、Cache
ファサードへの呼び出しをモックできます。ファサードは実際にはLaravelサービスコンテナによって解決および管理されるため、通常の静的クラスよりもはるかにテストしやすいです。たとえば、Cache
ファサードのget
メソッドへの呼び出しをモックしてみましょう。
<?php use Illuminate\Support\Facades\Cache; test('get index', function () { Cache::shouldReceive('get') ->once() ->with('key') ->andReturn('value'); $response = $this->get('/users'); // ...});
<?php namespace Tests\Feature; use Illuminate\Support\Facades\Cache;use Tests\TestCase; class UserControllerTest extends TestCase{ public function test_get_index(): void { Cache::shouldReceive('get') ->once() ->with('key') ->andReturn('value'); $response = $this->get('/users'); // ... }}
Request
ファサードをモックしないでください。代わりに、テストを実行するときに、get
やpost
などのHTTPテストメソッドに目的の入力を渡してください。同様に、Config
ファサードをモックする代わりに、テストでConfig::set
メソッドを呼び出してください。
ファサードスパイ
ファサードをスパイしたい場合は、対応するファサードでspy
メソッドを呼び出すことができます。スパイはモックに似ています。ただし、スパイはスパイとテスト対象のコード間の相互作用を記録し、コードの実行後にアサーションを行うことができます。
<?php use Illuminate\Support\Facades\Cache; test('values are be stored in cache', function () { Cache::spy(); $response = $this->get('/'); $response->assertStatus(200); Cache::shouldHaveReceived('put')->once()->with('name', 'Taylor', 10);});
use Illuminate\Support\Facades\Cache; public function test_values_are_be_stored_in_cache(): void{ Cache::spy(); $response = $this->get('/'); $response->assertStatus(200); Cache::shouldHaveReceived('put')->once()->with('name', 'Taylor', 10);}
時間との対話
テスト時、now
やIlluminate\Support\Carbon::now()
などのヘルパーによって返される時間を変更する必要がある場合があります。幸いなことに、Laravelのベース機能テストクラスには、現在の時間を操作できるヘルパーが含まれています。
test('time can be manipulated', function () { // Travel into the future... $this->travel(5)->milliseconds(); $this->travel(5)->seconds(); $this->travel(5)->minutes(); $this->travel(5)->hours(); $this->travel(5)->days(); $this->travel(5)->weeks(); $this->travel(5)->years(); // Travel into the past... $this->travel(-5)->hours(); // Travel to an explicit time... $this->travelTo(now()->subHours(6)); // Return back to the present time... $this->travelBack();});
public function test_time_can_be_manipulated(): void{ // Travel into the future... $this->travel(5)->milliseconds(); $this->travel(5)->seconds(); $this->travel(5)->minutes(); $this->travel(5)->hours(); $this->travel(5)->days(); $this->travel(5)->weeks(); $this->travel(5)->years(); // Travel into the past... $this->travel(-5)->hours(); // Travel to an explicit time... $this->travelTo(now()->subHours(6)); // Return back to the present time... $this->travelBack();}
さまざまなタイムトラベルメソッドにクロージャを提供することもできます。クロージャは、指定された時間に時間がフリーズされた状態で呼び出されます。クロージャが実行されると、時間は通常どおりに再開されます。
$this->travel(5)->days(function () { // Test something five days into the future...}); $this->travelTo(now()->subDays(10), function () { // Test something during a given moment...});
freezeTime
メソッドは、現在の時間をフリーズするために使用できます。同様に、freezeSecond
メソッドは、現在の時間をフリーズしますが、現在の秒の開始時にフリーズします。
use Illuminate\Support\Carbon; // Freeze time and resume normal time after executing closure...$this->freezeTime(function (Carbon $time) { // ...}); // Freeze time at the current second and resume normal time after executing closure...$this->freezeSecond(function (Carbon $time) { // ...})
ご想像のとおり、上記で説明したすべてのメソッドは、ディスカッションフォーラムで非アクティブな投稿をロックするなど、時間依存のアプリケーション動作をテストするのに主に役立ちます。
use App\Models\Thread; test('forum threads lock after one week of inactivity', function () { $thread = Thread::factory()->create(); $this->travel(1)->week(); expect($thread->isLockedByInactivity())->toBeTrue();});
use App\Models\Thread; public function test_forum_threads_lock_after_one_week_of_inactivity(){ $thread = Thread::factory()->create(); $this->travel(1)->week(); $this->assertTrue($thread->isLockedByInactivity());}