Laravel で PHPUnit を使うには


Laravel で PHPUnit

起動編

前提
Laravel5.5 利用

  • まずは使ってみる

「vendor/bin/phpunit」を実行
(デフォルトで)登録されているテストコードを実行するようになっている

$ cd laravel
$ ./vendor/bin/phpunit 
You need to set up the project dependencies using Composer:

    composer install

You can learn all about Composer on https://getcomposer.org/.

エラー?

どうやら vendor以下を削除して、composer install をする必要があるようです
僕は vendor/bin のみ削除してやり直したらうまくいきました。

$ rm -rf vendor/bin
$ composer install
~
Package manifest generated successfully.

サンプルテスト編

もう一度、「vendor/bin/phpunit」を実行

$ cd laravel
$ ./vendor/bin/phpunit
PHPUnit 6.5.7 by Sebastian Bergmann and contributors.

F.                    2 / 2 (100%)

Time: 317 ms, Memory: 14.00MB

There was 1 failure:

1) Tests\Feature\ExampleTest::testBasicTest
Expected status code 200 but received 302.
Failed asserting that false is true.

/~/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:78
/~/tests/Feature/ExampleTest.php:19

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.

エラー2

このデフォルトのテストは、真っ白なインストールしたての laravel 用のテストであり、
僕のようにある程度構築し終わってるとこのようにエラーにされます。
結論からいうと、認証系の処理を入れていたため「/」のときにリダイレクトされてステータスコードが302になっていたからということでした。
なので、ソースコードを以下のように変更します。

tests/Feature/ExampleTest.php
class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

 -      $response->assertStatus(200);
 +      $response->assertStatus(302);  // ステータスコードを変更
    }
}

僕のような凡ミスはさておき、基本は storage\logs\laravel.log に出力されるそうなので、
そちらを確認してうまいこと解決策を見出してください。

成功しました。

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

..                    2 / 2 (100%)

Time: 284 ms, Memory: 14.00MB

OK (2 tests, 2 assertions)

実行編

  • テスト全実行
./vendor/bin/phpunit
  • テスト単体実行
./vendor/bin/phpunit tests/Feature/LoginTest.php
  • テスト作成
php artisan make:test LoginTest
php artisan make:test UserTest --unit   # unit方のテストをするときはこちら