経緯
Laravel使ったAPIサーバーを立てていて、いつもPHPUnitの実行コマンド忘れてたのでartisanコマンドに登録しようと思い作ってみました。
前提
Laravel5.4
作ってみる
-
コマンドを作成する
shell$ php artisan make:command PhpUnit
こんな感じで出来上がります。
app/ ├── Console │ ├── Commands │ │ └── PhpUnit.php
-
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'))); } }
私は全実行かファイル名指定でしか実行しないのでファイル名指定だけ追加していますが、他のオプションも使われる方はその他オプション分も実装が必要です。
-
Kernel.phpに追加する
app/Console/Kernel.phpprotected $commands = [ Commands\PhpUnit::class ];
-
実行する
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コマンドに統合していきたいなと思いました。