イントロダクションIntroduction
Laravelはユニットテストも考慮して構築されています。実際、PHPUnitをサポートしており、最初から含まれています。アプリケーションのために、phpunit.xmlファイルも最初から準備されています。Laravel is built with unit 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.
サンプルのテストファイルがtestsディレクトリーに提供されています。新しいLaravelアプリケーションをインストールした後に、そのままphpunitをコマンドラインで実行し、試してみてください。An example test file is provided in the tests directory. After installing a new Laravel application, simply run phpunit on the command line to run your tests.
テスト定義と実行Defining & Running Tests
テストケースを作成するには、testsディレクトリーにファイルを作成してください。テストケースはTestCaseを拡張してください。それから通常はPHPUnitを使用して、テストメソッドを定義します。To create a test case, simply create a new test file in the tests directory. The test class should extend TestCase. You may then define test methods as you normally would when using PHPUnit.
テストケース例An Example Test Class
class FooTest extends TestCase {
public function testSomethingIsTrue()
{
$this->assertTrue(true);
}
}
アプリケーションの全テストは、端末でphpunitコマンドを実行することにより行われます。You may run all of the tests for your application by executing the phpunit command from your terminal.
setUpメソッドを定義する場合は、parent::setUpを確実に呼び出してください。Note: If you define your ownsetUpmethod, be sure to callparent::setUp.
テスト環境Test Environment
テスト実行時にLaravelは、設定環境を自動的にtestingへセットします。そして、Laravelはsessionとcacheの設定ファイルをテスト環境で呼び出します。両方のドライバーはテスト環境ではarrayにセットされます。これが意味するのはデータはテストを実行している間のみ存在しているということです。必要であれば、他のテスト設定環境を自由に作成することもできます。When running unit tests, Laravel will automatically set the configuration environment to testing. Also, Laravel includes configuration files for session and cache in the test environment. Both of these drivers are set to array while in the test environment, meaning no session or cache data will be persisted while testing. You are free to create other testing environment configurations as necessary.
testing環境変数は、phpunit.xmlファイルの中で設定されています。The testing environment variables may be configured in the phpunit.xml file.
テストからルートを呼び出すCalling Routes From Tests
テストからルートを呼び出すCalling A Route From A Test
テストでルートを呼び出すのは簡単で、callメソッドを使用します。You may easily call one of your routes for a test using the call method:
$response = $this->call('GET', 'user/profile');
$response = $this->call($method, $uri, $parameters, $cookies, $files, $server, $content);
その後、Illuminate\Http\Responseオブジェクトを調べます。You may then inspect the Illuminate\Http\Response object:
$this->assertEquals('Hello World', $response->getContent());
テストからコントローラーを呼び出すCalling A Controller From A Test
コントローラーをテストから呼び出すこともできます。You may also call a controller from a test:
$response = $this->action('GET', 'HomeController@index');
$response = $this->action('GET', 'UserController@profile', ['user' => 1]);
注目:
actionメソッドを使うときにも、コントローラーの完全な名前空間を指定する必要はありません。App\Http\Controllers名前空間に続く以降のクラス名だけを指定してください。Note: You do not need to specify the full controller namespace when using theactionmethod. Only specify the portion of the class name that follows theApp\Http\Controllersnamespace.
getContentメソッドはレスポンスのコンテンツ文字列を評価し、リターンします。ルートがビュー('View')をリターンするときは、originalプロパティーを使用し、ビューに渡した内容へアクセスできます。The getContent method will return the evaluated string contents of the response. If your route returns a View, you may access it using the original property:
$view = $response->original;
$this->assertEquals('John', $view['name']);
HTTPSルートを呼び出す場合、callSecureメソッドを使用します。To call a HTTPS route, you may use the callSecure method:
$response = $this->callSecure('GET', 'foo/bar');
ファサードのモックMocking Facades
テストをしているとLaravelの静的なファサード呼び出しのモックが必要となることが多いでしょう。例えば、次のコントローラーアクションを考えてみてください。When testing, you may often want to mock a call to a Laravel static facade. For example, consider the following controller action:
public function getIndex()
{
Event::fire('foo', ['name' => 'Dayle']);
return '全部おしまい!';
}
ファサードに対しshouldReceiveメソッドを使用することで、Eventクラスの呼び出しをモックすることができます。これはMockeryのインスタンスをリターンします。We can mock the call to the Event class by using the shouldReceive method on the facade, which will return an instance of a Mockery[https://github.com/padraic/mockery] mock.
ファサードをモックMocking A Facade
public function testGetIndex()
{
Event::shouldReceive('fire')->once()->with('foo', ['name' => 'Dayle']);
$this->call('GET', '/');
}
注意:
Requestファサードに対してモックは使わないでください。その代わりにテストを実行する場合は、callメソッドに希望する入力を渡してください。Note: You should not mock theRequestfacade. Instead, pass the input you desire into thecallmethod when running your test.
フレームワーク関連Framework Assertions
Laravelにはテストを多少簡単にするために、いくつかのassertメソッドが用意されています。Laravel ships with several assert methods to make testing a little easier:
レスポンスがOKであることを確認Asserting Responses Are OK
public function testMethod()
{
$this->call('GET', '/');
$this->assertResponseOk();
}
レスポンス状態を確認Asserting Response Statuses
$this->assertResponseStatus(403);
レスポンスがリダイレクトであることを確認Asserting Responses Are Redirects
$this->assertRedirectedTo('foo');
$this->assertRedirectedToRoute('route.name');
$this->assertRedirectedToAction('Controller@method');
ビューがデーターを持っていることを確認Asserting A View Has Some Data
public function testMethod()
{
$this->call('GET', '/');
$this->assertViewHas('name');
$this->assertViewHas('age', $value);
}
セッションにデーターが存在することを確認Asserting The Session Has Some Data
public function testMethod()
{
$this->call('GET', '/');
$this->assertSessionHas('name');
$this->assertSessionHas('age', $value);
}
セッションがエラーを持っているか確認Asserting The Session Has Errors
public function testMethod()
{
$this->call('GET', '/');
$this->assertSessionHasErrors();
// 指定されたキーのエラーがセッションに存在するか確認…
$this->assertSessionHasErrors('name');
// 複数のエラーがセッションに存在するか確認…
$this->assertSessionHasErrors(['name', 'age']);
}
直前の入力のデーターの確認Asserting Old Input Has Some Data
public function testMethod()
{
$this->call('GET', '/');
$this->assertHasOldInput();
}
ヘルパメソッドHelper Methods
TestCaseクラスはアプリケーションのテストが簡単にできるように、ヘルパをいくつか用意しています。The TestCase class contains several helper methods to make testing your application easier.
テスト中でセッションの設定、フラッシュSetting And Flushing Sessions From Tests
$this->session(['foo' => 'bar']);
$this->flushSession();
認証済みユーザーの設定Setting The Currently Authenticated User
認証済みユーザーをセットしたい場合は、beメソッドを使用してください。You may set the currently authenticated user using the be method:
$user = new User(['name' => 'John']);
$this->be($user);
データベースの内容を再構築したい場合は、seedメソッドを使用します。You may re-seed your database from a test using the seed method:
テストでデータベース初期値設定の再実行Re-Seeding Database From Tests
$this->seed();
$this->seed('DatabaseSeeder');
初期値設定クラス(seed)の作成についてはドキュメントのマイグレーションと初期値設定の章をご覧ください。More information on creating seeds may be found in the migrations and seeding[/docs/migrations#database-seeding] section of the documentation.
アプリケーションのリフレッシュRefreshing The Application
既にご存知の通り、Laravelのアプリケーション、つまりサービスコンテナへは、テストメソッドの中から$this->appにより、いつでもアクセスできます。このサービスコンテナインスタンスは、それぞれのテストクラスごとにリフレッシュされます。特定のメソッドでアプリケーションを強制的にリフレッシュしたい場合は、refreshApplicationメソッドをテストメソッドで呼び出して下さい。これにより、テストケースが実行されたことにより、サービスコンテナに追加されたモックのような追加結合をリセットします。As you may already know, you can access your Application (service container[/docs/{{version}}/container]) via $this->app from any test method. This service container instance is refreshed for each test class. If you wish to manually force the Application to be refreshed for a given method, you may use the refreshApplication method from your test method. This will reset any extra bindings, such as mocks, that have been placed in the IoC container since the test case started running.