LaravelのPHPUnitでAPIのコントローラに対するテストコードを書いた忘備録。
例はコメントのCRUD操作。
/tests/Feature/ApiCommentControllerTest.php
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Classes\User\Session;
class ApiCommentControllerTest extends TestCase
{
protected $user_session_id;
function setUp(): void
{
parent::setUp();
// アプリ側で$_SERVER変数や$_REQUEST変数を利用している場合は明示する必要がある
$_SERVER['REQUEST_URI'] = 'XXXX';
$_REQUEST['s'] = (new Session)->create(1);
$this->user_session_id = $_REQUEST['s'];
}
public function testCreateComment()
{
$response = $this->post(
'/api/comment/create',
[
'post_id' => 1,
'user_id' => 1,
'comment' => 'auto test',
's' => $this->user_session_id
]
);
$response->dump();
$response->assertStatus(200);
}
public function testListComment()
{
$response = $this->post(
'/api/comment/list',
[
's' => $this->user_session_id
]
);
$response->dump();
$response->assertStatus(200);
}
public function testUpdateComment()
{
$response = $this->post(
'/api/comment/update',
[
'id' => 1
'post_id' => 1,
'user_id' => 1,
'comment' => 'auto test update',
's' => $this->user_session_id,
]
);
$response->dump();
$response->assertStatus(200);
}
public function testDeleteComment()
{
$response = $this->post(
'/api/comment/delete',
[
'id' => 1
's' => $this->user_session_id,
]
);
$response->dump();
$response->assertStatus(200);
}
}
実行
$ php artisan route:cache
$ ./vendor/bin/phpunit
#もしくは $ composer exec phpunit