LoginSignup
6
6

More than 5 years have passed since last update.

Laravelでartisan使ってPHPUnitを実行する

Posted at

経緯

Laravel使ったAPIサーバーを立てていて、いつもPHPUnitの実行コマンド忘れてたのでartisanコマンドに登録しようと思い作ってみました。

前提

Laravel5.4

作ってみる

  1. コマンドを作成する

    shell
    $ php artisan make:command PhpUnit
    

    こんな感じで出来上がります。

    app/
    ├── Console
    │   ├── Commands
    │   │   └── PhpUnit.php
    
  2. PhpUnit.phpに実行するコマンドを実装する

    app/Console/Commands/PhpUnit.php
    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    
    class PhpUnit extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'test {file_name?}';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'phpunitを実行する.ファイルを指定する場合は引数にファイル名を指定する';
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            $this->info(shell_exec("vendor/bin/phpunit " . $this->argument('file_name')));
        }
    }
    

    私は全実行かファイル名指定でしか実行しないのでファイル名指定だけ追加していますが、他のオプションも使われる方はその他オプション分も実装が必要です。

  3. Kernel.phpに追加する

    app/Console/Kernel.php
    protected $commands = [
        Commands\PhpUnit::class
    ];
    
  4. 実行する

    shell
    // 全実行
    $ php artisan test
    // ファイル名指定
    $ php artisan test tests/Unit/SampleTest.php
    

    いつもと同様に実行結果が出力されます。

    $ php artisan test tests/Unit/SampleTest.php
    PHPUnit 5.7.19 by Sebastian Bergmann and contributors.
    
        .                                                                   1 / 1 (100%)
    
    Time: 2.84 seconds, Memory: 16.00MB
    
    OK (1 test, 2 assertions)
    
    Generating code coverage report in Clover XML format ... done
    
    Generating code coverage report in HTML format ... done
    

さいごに

コマンド忘れても php artisan list ですぐに見れるのでよく使うコマンドは全部artisanコマンドに統合していきたいなと思いました。

6
6
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
6
6