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