LaravelでStorageのtemporaryUrlをモック化する方法

Laravelを使用していると、S3ストレージのtemporaryUrlメソッドを利用する場面が出てきます。

しかし、ユニットテスト環境では実際のS3にアクセスするのではなく、このtemporaryUrlをモック化してテストを行いたい場合があります。

本記事では、LaravelのStorageファサードを使用してtemporaryUrlをモック化する方法をご紹介します。

動機

通常、StoragetemporaryUrlは指定したファイルに対する一時的なアクセス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');

解説

  1. Storage::shouldReceive('disk')->with('s3')->andReturnSelf();
    Storage::disk('s3')が呼び出されたときに、Storageのモックインスタンス自身を返します。これにより、チェーンメソッドを使用する際にモックを適切に動作させることができます。

  2. Storage::shouldReceive('temporaryUrl')
    temporaryUrlが呼び出されたときに、指定したURLを返すように設定します。引数としてファイル名(example.jpg)とDateTimeInterface型のインスタンスが期待されます。

モック化を活用したテスト例

以下は、StoragetemporaryUrlをモック化し、ユニットテストで利用する例です。

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メソッドをモック化でき、ストレージ関連のコードを効率よくテストできるようになります。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.