イントロダクションIntroduction
Laravelはユニットテストも考慮して構築されています。実際、PHPUnitをサポートしており、最初から含まれています。アプリケーションのためにphpunit.xml
ファイルも最初から準備されています。さらにフレームワークはアプリケーションを記述的にテストするために便利なヘルパメソッドも持っています。Laravel is built with testing in
mind. In fact, support for testing with PHPUnit is
included out of the box and a
phpunit.xml
file is already setup for
your application. The framework also ships with
convenient helper methods that allow you to
expressively test your applications.
ExampleTest.php
ファイルがtests
ディレクトリに提供されています。新しいLaravelアプリケーションをインストールした後、そのままphpunit
をコマンドラインで実行し試してみてください。An ExampleTest.php
file is provided in the tests
directory. After installing a new Laravel
application, simply run phpunit
on the
command line to run your tests.
環境Environment
テスト実行時にLaravelは、設定環境を自動的にtesting
へセットします。そしてLaravelはセッションととキャッシュの設定ファイルをテスト環境で呼び出します。両方のドライバはテスト環境ではarray
にセットされます。つまりデータはテストを実行している間のみ存在しているということです。When running tests, Laravel will
automatically set the configuration environment to
testing
. Laravel automatically
configures the session and cache to the
array
driver while testing, meaning no
session or cache data will be persisted while
testing.
必要であれば他のテスト設定環境を自由に作成することもできます。testing
動作環境変数はphpunit.xml
の中で設定されています。テスト実行前には、config:clear
Artisanコマンドを実行し、設定キャッシュをクリアするのを忘れないでください。You are free to define other
testing environment configuration values as
necessary. The testing
environment
variables may be configured in the
phpunit.xml
file, but make sure to
clear your configuration cache using the
config:clear
Artisan command before
running your tests!
テストの生成と実行Creating & Running Tests
新しいテストケースを作成するには、make:test
Artisanコマンドを使います。To create a
new test case, use the make:test
Artisan command:
php artisan make:test UserTest
上記のコマンドにより、tests
ディレクトリ中に新しいUserTest
クラスが設置されます。それから、いつもの通りPHPUnitを使ってテストメソッドを定義してください。テストを実行するには、ただターミナルでphpunit
コマンドを実行するだけです。This command will place a new
UserTest
class within your
tests
directory. You may then define
test methods as you normally would using PHPUnit. To
run your tests, simply execute the
phpunit
command from your
terminal:
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UserTest extends TestCase
{
/**
* 基本的なテスト例
*
* @return void
*/
public function testExample()
{
$this->assertTrue(true);
}
}
Note:
テストクラスに独自のsetUp
メソッドを定義する場合は、parent::setUp
を確実に呼び出してください。{note} If you define your ownsetUp
method within a test class, be sure to callparent::setUp
.