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?

Laravelのユニットテスト(初歩編)

Posted at

はじめに

Laravelでテストを書く最初の一歩として簡単なユニットテストの
サンプルを自分用に残そうと思います。
サンプルではDBを使わないシンプルなユニットテストを記載します。

1. 準備

php artisan make:testコマンドでテストクラスを作成します。
今回は例として、BlogPostモデルのテストを書きます。

BlogPostモデル(例)

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class BlogPost extends Model
{
    protected $fillable = [
        'title',
        'content',
        'author',
        'status'
    ];

    public function isPublished(): bool
    {
        return $this->status === 'published';
    }

    public function getExcerpt(int $length = 100): string
    {
        return mb_substr($this->content, 0, $length) . '...';
    }
}

2. ユニットテストの作成

tests/Unit/BlogPostTest.php にテストクラスを作成します。
php artisan make:test BlogPostTest --unitで作成します。
テスト内容を記載します。今回は2つのケースをテストします。

namespace Tests\Unit;

use App\Models\BlogPost;
use Tests\TestCase;

class BlogPostTest extends TestCase
{
    /** @test */
    public function test_postがpublishedである()
    {
        $post = new BlogPost([
            'title' => 'テスト投稿',
            'content' => 'これはテスト投稿です。',
            'author' => 'テストユーザー',
            'status' => 'published'
        ]);

        $this->assertTrue($post->isPublished());
    }

    /** @test */
    public function test_postのcontentからexcerptを取得できる()
    {
        $post = new BlogPost([
            'title' => 'テスト投稿',
            'content' => 'これは長いテスト投稿の内容です。テストテスト',
            'author' => 'テストユーザー',
            'status' => 'draft'
        ]);

        $excerpt = $post->getExcerpt(20);
        $this->assertEquals('これは長いテスト投稿の内容です。テストテ...', $excerpt);
    }
}

3. テストの実行

以下のコマンドでテストを実行できます。
画像の様にPASSとなればOKです。

php artisan test tests/Unit/BlogPostTest.php

スクリーンショット 2025-05-29 17.13.16.png

あとがき

今回はユニットテストの初歩の記事で投稿しました。
今後簡単なfeatureテストやmockについても書いて行こうと思います。
(この記事はAIに壁打ちしながら作成したものとなります。)

おまけ

LaravelでPHPUnitのカバレッジ機能を使用してテストカバレッジを測定できます。

カバレッジレポートの生成

以下のコマンドでカバレッジレポートを生成できます。
今回のコードではメソッドが2つありそれぞれにテストを書いたので100%となっています。
例えば1つ目のケースをコメントアウトした場合は50%となります。
1つのメソッドに複数のテストケースを書いた場合もメソッドごとのカバー率なのであくまでそのメソッドのテストがあるかどうかの目安となります。

php artisan test --coverage

スクリーンショット 2025-05-29 17.36.53.png

注意点

  • カバレッジレポートはプロジェクト全体のテストカバレッジを測定します
  • 単一ファイルのカバレッジ測定はできません
  • カバレッジレポートを生成するには、XdebugまたはPCOVのインストールが必要です
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?