背景
JSONをPOSTのボディで受けるAPIのテストを書きたかった
ポイント
テストクラスの $this->json() に配列を渡すとJSONにしてリクエストしてくれる。
使い方はサンプル実装参照。
レスポンスの検証は seeJson() や seeJsonEquals() を使うと良い。
検証メソッドについてはリファレンスを見るのが一番。
https://laravel.com/api/5.2/Illuminate/Foundation/Testing/TestCase.html#method_json
準備
テストコードを artisan で作成
php artisan make:test TagsControllerTest
サンプル実装
TagsControllerTest.php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class TagsControllerTest extends TestCase
{
use WithoutMiddleware;
/**
* A basic test example.
*
* @return void
*/
public function testSearch()
{
$params = [
'type' => 'item',
'tag' => 'ボーダー',
'limit' => 10,
'offset' => 0
];
$headers = [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
];
$this->json('POST', '/api/v1/tags/search', $params, $headers)
->seeJson(
[
"tag" => "ボーダー"
]
);
}
}
テスト実施
プロジェクトのルートにて、以下をシェルより実行するだけ
./vendor/bin/phpunit
成功していれば以下のような結果となる
PHPUnit 4.8.35 by Sebastian Bergmann and contributors.
.
Time: 5.4 seconds, Memory: 13.25MB
OK (1 test, 1 assertion)