Laravelを使用していると、S3ストレージのtemporaryUrl
メソッドを利用する場面が出てきます。
しかし、ユニットテスト環境では実際のS3にアクセスするのではなく、このtemporaryUrl
をモック化してテストを行いたい場合があります。
本記事では、LaravelのStorage
ファサードを使用してtemporaryUrl
をモック化する方法をご紹介します。
動機
通常、Storage
のtemporaryUrl
は指定したファイルに対する一時的なアクセスURLを生成します。
しかし、ユニットテストでは外部サービス(この場合はAWS S3)に依存することなくテストを完結させたいものです。
そのため、temporaryUrl
メソッドをモック化し、意図した値を返すように設定する必要があります。
モック化の手順
以下のコードスニペットは、Storage
ファサードをモック化し、temporaryUrl
メソッドが指定したURLを返すように設定する方法を示しています。
Storage::shouldReceive('disk')
->with('s3')
->andReturnSelf();
Storage::shouldReceive('temporaryUrl')
->with('example.jpg', Mockery::type(\DateTimeInterface::class))
->andReturn('https://example.com/temp-url/example.jpg');
解説
Storage::shouldReceive('disk')->with('s3')->andReturnSelf();
Storage::disk('s3')
が呼び出されたときに、Storage
のモックインスタンス自身を返します。これにより、チェーンメソッドを使用する際にモックを適切に動作させることができます。-
Storage::shouldReceive('temporaryUrl')
temporaryUrl
が呼び出されたときに、指定したURLを返すように設定します。引数としてファイル名(example.jpg
)とDateTimeInterface
型のインスタンスが期待されます。
モック化を活用したテスト例
以下は、Storage
のtemporaryUrl
をモック化し、ユニットテストで利用する例です。
public function testTemporaryUrl()
{
// モック設定
Storage::shouldReceive('disk')
->with('s3')
->andReturnSelf();
Storage::shouldReceive('temporaryUrl')
->with('example1.jpg', Mockery::type(DateTimeInterface::class))
->andReturn('https://example.com/temp-url/example1.jpg');
Storage::shouldReceive('temporaryUrl')
->with('example2.jpg', Mockery::type(DateTimeInterface::class))
->andReturn('https://example.com/temp-url/example2.jpg');
// テスト: モック化されたURLの確認
$url = Storage::disk('s3')->temporaryUrl('example1.jpg', now()->addMinutes(5));
$this->assertEquals('https://example.com/temp-url/example1.jpg', $url);
$url = Storage::disk('s3')->temporaryUrl('example2.jpg', now()->addMinutes(5));
$this->assertEquals('https://example.com/temp-url/example2.jpg', $url);
}
テストのポイント
- モック化により、実際にAWS S3に接続することなくテストを実行できます。
- ファイル名や日付の引数ごとに返されるURLを自由に設定可能です。
- テストの結果を保証するため、モック化したURLを
assertEquals
で検証します。
まとめ
Laravelのユニットテストで外部ストレージの依存を排除することは、テストの信頼性とスピードを向上させます。
今回紹介した方法を活用すれば、簡単にtemporaryUrl
メソッドをモック化でき、ストレージ関連のコードを効率よくテストできるようになります。