ユニットテストの基本
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>
XMLvendor/bin/phpunit --coverage-html coverage
Bashテストの並列実行
phpunit.xml
<phpunit>
<php>
<env name="PARALLEL_TESTS" value="true"/>
</php>
</phpunit>
XMLphp artisan test --parallel
Bash
コメント