はじめに
こんにちは、エンジニアのkeitaMaxです。
今回は、以前作成したLaravelの環境をつかってコードテストを書いていきます。
Laravelの公式サイトをもとに、PHPUnitを使用してテストコードを作成していきたいと思います。
インストール
Laravelはユニットテストも考慮して構築されています。実際、PHPUnitをサポートしており、最初から含まれています。
(引用元:https://readouble.com/laravel/10.x/ja/testing.html)
Laravel公式サイトによると、PHPUnitが最初から含まれているということなので、PHPUnitを使用したいと思っても新しく何かをインストールする不必要はなさそうです。
テストを作成する
以下のようなコマンドを実行してあたらしいテストケースを作成します。
php artisan make:test PostTest
すると、tests/Feature
ディレクトリはいかにPostTest
ファイルが作成されます。
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class PostTest extends TestCase
{
/**
* A basic feature test example.
*/
public function test_example(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
テストを実行する
作成したテストケースを実行するには以下のコマンドで実行して下さい。
php artisan test
実行結果は以下のようになります、
PASS Tests\Unit\ExampleTest
✓ that true is true 0.01s
PASS Tests\Feature\ExampleTest
✓ the application returns a successful response 0.13s
PASS Tests\Feature\PostTest
✓ example 0.01s
Tests: 3 passed (3
最初からあるExampleTest
と一緒に今回作成したPostTest
も一緒に実行されていて、すべてのテストがPASSしていることがわかります。
テストを失敗させてみる
今度はテストを失敗させてみます。
/users
という作成していないURLをたたかせて失敗させてみます。
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class PostTest extends TestCase
{
/**
* A basic feature test example.
*/
public function test_example(): void
{
$response = $this->get('/users'); //変更したとこ
$response->assertStatus(200);
}
}
このように修正しテストを実行してみると、
PASS Tests\Unit\ExampleTest
✓ that true is true 0.01s
PASS Tests\Feature\ExampleTest
✓ the application returns a successful response 0.13s
FAIL Tests\Feature\PostTest
⨯ example 0.03s
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
FAILED Tests\Feature\PostTest > example
Expected response status code [200] but received 404.
Failed asserting that 404 is identical to 200.
at tests/Feature/PostTest.php:18
14▕ public function test_example(): void
15▕ {
16▕ $response = $this->get('/users');
17▕
➜ 18▕ $response->assertStatus(200);
19▕ }
20▕ }
21▕
Tests: 1 failed, 2 passed (3 assertions)
Duration: 0.24s
このように、先ほど修正した箇所でFailedしていることがわかります。
おまけで、'/users'を叩いた時に404が返ってくるので、404が返ってくることを確認するテストコードを書きます。
$response->assertStatus(404);
にしてみて実際にテストコードを流すと、
PASS Tests\Unit\ExampleTest
✓ that true is true
PASS Tests\Feature\ExampleTest
✓ the application returns a successful response 0.10s
PASS Tests\Feature\PostTest
✓ example 0.01s
Tests: 3 passed (3 assertions)
Duration: 0.16s
となりテストコードが通っていることがわかりました。
おわりに
かなり簡単にテストコードがかけることがわかりました。
次はPHPUnitを使用していろいろなテストケースを作成していきたいと思います。
やり方が違ったり、もっといいやり方があるというご指摘がある方はコメントしていただけると幸いです。
最後まで読んでいただきありがとうございました。
参考文献