0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

todoアプリのテストをする時、何をテストすればいいのか

Posted at

todoアプリを作成していて、どんなテストをすれば良いのかわからなかったので、それを軽くまとめてみました。

現状のテストコードはこんな感じ

<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use App\Models\Todo;
use Tests\TestCase;

class APITest extends TestCase
{
    use DatabaseTransactions;
    private $todo;

    public function setUp() :void
    {
        parent::setUp();

        $this->todo = Todo::factory()->create();
    }
    public function test_todo作成(): void
    {
		$response = $this->postJson('/todosCreated');
		$response->assertStatus(200);
    }
...
}

todoを作成したことを確認して、そのレスポンスが200を返すことを確認するだけのテスト。

※とりあえず、テストが通っていることを確認するテストだったので、あまり意味はない。

todoが実際に作成されているか、レスポンスの中身についてはテストができていないので、その辺を追加する必要がありそう。

やってみたこと

  • Todoがデータベースに正しく保存されているかの確認
  • レスポンスの内容を検証

Todoがデータベースに正しく保存されているかの確認

assertDatabaseHasを使用する事で、todoの期待される属性を指定。

public function test_todo作成(): void
    {
        $aaa = $this->assertDatabaseHas('todos', [
            'title' => $this->todo->title,
            'status' => $this->todo->status,
            'created_at' => $this->todo->created_at,
            'updated_at' => $this->todo->updated_at
        ]);

		$response = $this->postJson('/todosCreated');
		$response->assertStatus(200);
    }

コマンドを実行。

php artisan test --filter test_todo作成 tests/Feature/APITest.php --testdox

**--filter**オプションを使用すると、特定のテストメソッドを実行できます。それには特定のテストメソッド名を指定する必要がある。

**--testdox**オプションを使用すると、テストメソッド名の代わりに、テストの説明文が表示されます。これにより、テストの結果がわかりやすく表示される。

実行結果↓↓↓

スクリーンショット 2023-10-22 13.33.26.png

レスポンスの内容を確認

レスポンスの中身を確認するには、assertJsonStructureを使用して、期待されるレスポンスをJSON構造で確認します。

public function test_todo作成(): void
    {
        $this->assertDatabaseHas('todos', [
            'title' => $this->todo->title,
            'status' => $this->todo->status,
            'created_at' => $this->todo->created_at,
            'updated_at' => $this->todo->updated_at
        ]);

		$response = $this->postJson('/todosCreated');
		$response->assertStatus(200);

        $response->assertJsonStructure([
            'title',
            'status',
            'created_at',
            'updated_at',
            'id'
        ]);
    }
...

※コマンドはさっきと同じ。

実行結果↓↓↓

スクリーンショット 2023-10-22 15.36.04.png

これで、一先ずtodo作成時のテスト実装は完了!!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?