LoginSignup
8
3

More than 1 year has passed since last update.

【laravel】ユニットテストざっくり

Posted at

概要

laravelでは下記テストが用意されている。

  • ユニットテスト /tests/Unit
    クラスやメソッドなどモジュール単位で動作を検証する

  • フィーチャテスト /tests/Feature
    WebページやAPI機能など
    コントローラの動き(リクエストを受けてレスポンスを返すまで)を検証する

今回はユニットテスト練習用を作成した際のまとめ。

テスト対象の作成

sample.php
   public function sample(int $english, int $math, int $science)
    {
        $average = ($english + $math + $science) / 3;
        //3教科の平均でクラス分け
        if ($average >= 85) {
            $class = 'advance';
        } else {
            $class = 'basic';
        }
        return array($average, $class);
    }

テストクラスの生成

make:testコマンドでテストクラス生成

php artisan make:test SampleTest --unit

// ディレクトリを指定してファイル作成
php artisan make:test User/SampleTest --unit

テストメソッドを作成する

アサーションメソッド使って作成していく

use App\Http\Controllers;
use Tests\TestCase;

class SampleTest extends TestCase
{
    /**
     * @test
     */
    public function sampleTest()
    {
        $result = (new Grouping)->grouping(90, 85, 80);
        $this->assertEquals($result[0], 85);
        $this->assertEquals($result[1], 'advance');
    }
}

テスト実行

./vendor/bin/phpunit tests/Unit/SampleTest.php
PHPUnit 9.5.24 #StandWithUkraine

..                                                                 
Time: 00:00.471, Memory: 20.00 MB
OK (2 tests, 2 assertions)

テスト結果に「OK」が表示されれば成功!
上記だと2つのテスト、2つのアサーションが実行されたことがわかる

以上、簡単までに。

8
3
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
8
3