LoginSignup
4
3

More than 3 years have passed since last update.

PHPUnitの導入

Last updated at Posted at 2021-02-11

早いうちにPHPUnitを学習して、1つ1つの機能を実装するたびにテストコードを追加していきたい。
RSpecよりかは準備が楽だった。

準備

mysql等でテスト用のDBを作成した後、
.env.testingという名のファイルを作成し、.envファイルからコピペしてDB名だけテスト用に書き換える。

.env.testing
DB_DATABASE=hoge_test  #作成したテストDB名

その後、

$ php artisan migrate --env=testing

を実行してテストDBに対してmigrateする。

composerのインストールを行なっていない人はインストールする。

$ composer install

Laravel のプロジェクトディレクトリ下で

$ ./vendor/bin/phpunit

を実行。

PHPUnit 9.5.2 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:01.199, Memory: 22.00 MB

OK (1 test, 1 assertion)

こんな感じで表示されればOK(下の数字はテスト数などで変わる)。

テストメソッドは、
・メソッド名の接頭辞に “test” をつけること
・メソッドのコメントに@testアノテーションをつけること
のどちらかが必要になる。
また、パブリックメソッドであることも必要。

実践

ユーザー登録のテストを行う。

テストファイルの作成

php artisan make:test UserTest

テストコードの記述

UserTest.php
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class UserTest extends TestCase
{

    use RefreshDatabase;

    /**
     * @test
     */
    public function createUser()
    {
        $user = new \App\Models\User;
        $user->name = "test";
        $user->email = "test@example.com";
        $user->password = \Hash::make('password');
        $user->save();

        $readUser = \App\Models\User::where('name', 'test')->first();

        // データが取得できたか
        $this->assertNotNull($readUser); 

        // パスワードが一致している
        $this->assertTrue(\Hash::check('password', $readUser->password));
    }
}

実行結果

$ ./vendor/bin/phpunit
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:01.774, Memory: 26.00 MB

OK (1 test, 2 assertions)

参考

https://php-junkie.net/framework/laravel/first-testing/
https://qiita.com/kuriya/items/4c9dbefc19514f415374
https://techacademy.jp/magazine/19301

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