Laravel逆引きTips – Test

Laravel Laravel

Laravel逆引きTIps一覧へ戻る

ユニットテストの基本

use Tests\TestCase;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    public function test_basic_test()
    {
        $this->assertTrue(true);

        $this->assertEquals(4, 2 + 2);

        $this->assertInstanceOf(User::class, new User);
    }
}
PHP

フィーチャーテスト(HTTP テスト)

    public function test_basic_request()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }

    public function test_user_can_login()
    {
        $user = User::factory()->create([
            'password' => Hash::make('password'),
        ]);

        $response = $this->post('/login', [
            'email' => $user->email,
            'password' => 'password',
        ]);

        $response->assertRedirect('/home');
        $this->assertAuthenticatedAs($user);
    }
PHP

データベーステスト

    public function test_database()
    {
        User::factory()->count(3)->create();

        $this->assertDatabaseCount('users', 3);

        $this->assertDatabaseHas('users', [
            'email' => 'test@example.com',
        ]);
    }
PHP

モックとスタブの使用

    public function test_mocking()
    {
        $mock = Mockery::mock('App\Services\PaymentGateway');
        $mock->shouldReceive('charge')
             ->once()
             ->with(100)
             ->andReturn(true);

        $this->app->instance('App\Services\PaymentGateway', $mock);

        $result = $this->app->make('App\Services\PaymentGateway')->charge(100);
        $this->assertTrue($result);
    }
PHP

テストカバレッジの計測

phpunit.xml
<coverage>
    <include>
        <directory suffix=".php">./app</directory>
    </include>
</coverage>
XML
vendor/bin/phpunit --coverage-html coverage
Bash

テストの並列実行

phpunit.xml
<phpunit>
    <php>
        <env name="PARALLEL_TESTS" value="true"/>
    </php>
</phpunit>
XML
php artisan test --parallel
Bash

Laravel逆引きTIps一覧へ戻る

コメント

タイトルとURLをコピーしました