メインコンテンツまでスキップ

モッキング

はじめに

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');

ファサードのモック

従来の静的メソッド呼び出しとは異なり、ファサードリアルタイムファサードを含む)はモックすることができます。これにより、従来の静的メソッドよりも優れたテスト可能性が提供され、従来の依存性注入を使用している場合と同じテスト可能性が得られます。テスト時には、コントローラーの中で発生する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 [
// ...
];
}
}

shouldReceiveメソッドを使用してCacheファサードへの呼び出しをモックすることができます。これにより、Mockeryモックのインスタンスが返されます。ファサードは実際には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ファサードをモックすべきではありません。代わりに、テストを実行する際にgetpostなどの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);
}

時間とのやり取り

テスト時には、nowIlluminate\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());
}