前提
下記に対してPHPUnitでテストを作成していきます。
LaravelでAPIを作成する
テストの設定
phpunit.xmlの設定
<server name="DB_DATABASE" value="TodoApp_testing"/>
上記のように記述されているため下記コマンドでテスト用の.envファイルを作成する
cp .env .env.testing
.env.testingに下記を記述する。(テスト用のデータベースを設定する)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=HogeApp_testing
DB_USERNAME=root
DB_PASSWORD=
テストの作成
テストディレクトリには以下の2つがあるが今回はAPIのテストなので①のテストを作成する
①Feature...一つのリクエストから始まる一連の流れをテスト
②Unit...クラスや関数の機能テスト
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use App\Models\Hoge;
class HogeTest extends TestCase
{
use RefreshDatabase; // データのキャッシュを消す
/**
* @test
* 上記のように記述することでメソッド名にtestを付けなくて良い
*/
public function CanGetAList()
{
$hoges = Hoge::factory()->count(10)->create();
$response = $this->getJson('api/hoges');
$response
->assertOk()
->assertJsonCount($hoges->count());
}
/**
* @test
*/
public function CanRegister()
{
$data = [
'title' => 'テスト投稿'
];
$response = $this->postJson('api/hoges', $data);
$response
->assertCreated()
->assertJsonFragment($data);
}
/**
* @test
*/
public function CanBeUpdated()
{
$hoge = Hoge::factory()->create();
$hoge->title = '書き換え';
$response = $this->patchJson("api/hoges/{$hoge->id}", $hoge->toArray());
$response
->assertOk()
->assertJsonFragment($hoge->toArray());
}
/**
* @test
*/
public function CanBeDeleted()
{
$hoges = Hoge::factory()->count(10)->create();
$response = $this->deleteJson("api/hoges/1");
$response->assertOk();
$response = $this->getJson("api/hoges");
$response->assertJsonCount($hoges->count() -1);
}
}
テストは下記のコマンドで実行する
./vendor/bin/phpunit tests/Feature/【テストファイル名】
実行するとpassしているのが分かります!
(もし全体のテストを実行してpassしなかった場合は1メソッドずつに分割して試してみてください。)