ラボ > Laravel、Lumen:テスト

laravel テストの共通処理の対応

ログイン処理などあちこちで必要になるテストをどっかに置いておきたい

作成日:2025-04-11, 更新日:2025-04-11

種類

  • 共通処理用のファイルを用意
  • 継承元を用意

ファイルの置き場所と「$ php artisan test」の実行対象

ファイルはどこに置いても良いらしい

「$ php artisan test」の実行対象

  • ファイル名が *Test.php で終わる
  • TestCase を継承したクラス
  • public function test●●●() というメソッドを持つ

とりあえずファイル名のルールだけ間違わなければテストの対象から外れるっぽい

共通処理用のファイルを用意

traitで用意して、useで読み込んで使う
とりあえず「tests\TestHelpers」の下にファイルを置く

共通処理用のファイル

namespace Tests\TestHelpers;
trait AuthTestHelper {
    protected function loginAsTestUser() {
        $data = [
            'memberid' => 'user@example.com',
            'password' => 'secret',
            '_token' => csrf_token(),
        ];

        $response = $this->post(route('login'), $data);
        $response->assertRedirect(route('dashboard'));
    }
}

共通処理用のファイルから読み込んで使う

namespace Tests\Feature;
use Tests\TestHelpers\AuthTestHelper;
class DashboardTest extends TestCase {
    use AuthTestHelper;

    public function test_show_dashboard() {
        $this->loginAsTestUser();
        $response = $this->get(route('dashboard'));
        $response->assertStatus(200);
    }
}

継承元を用意

とりあえず「tests\TestBase」の下にファイルを置く

継承元になるファイル

namespace Tests\TestBase;
use Tests\TestCase;
class TestHelperTestCase  extends TestCase {
    protected function loginAsTestUser() {
        $data = [
            'memberid' => 'user@example.com',
            'password' => 'secret',
            '_token' => csrf_token(),
        ];

        $response = $this->post(route('login'), $data);
        $response->assertRedirect(route('dashboard'));
    }
}

継承して使う

namespace Tests\Feature;
use Tests\TestBase\TestHelperTestCase;
class DashboardTest extends TestHelperTestCase {
    public function test_show_dashboard() {
        $this->loginAsTestUser();
        $response = $this->get(route('dashboard'));
        $response->assertStatus(200);
    }
}