イントロダクションIntroduction
Laravelはユニットテストも考慮して作られています。実際、最初からPHPUnitを含んでおり、アプリケーションにはphpunit.xml
ファイルを用意してあります。(訳注:現在はPHPUnitを取り込んでおらず、必要に応じてユーザーが読み込みます。)さらにPHPUnitに関してLaravelは、テスト時にブラウザーをシミュレートし、ビューを調査/操作できるように、SymfonyのHttpKernel、DomCrawler、BrowserKitコンポーネントを用意してあります。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. In addition to PHPUnit, Laravel
also utilizes the Symfony HttpKernel, DomCrawler,
and BrowserKit components to allow you to inspect
and manipulate your views while testing, allowing to
simulate a web browser.
サンプルのテストファイルがapp/tests
ディレクトリーに提供されています。新しいLaravelアプリケーションをインストールしたあとで、シンプルにphpunit
をコマンドラインで実行し、テストしてみてください。An example test file is provided
in the app/tests
directory. After
installing a new Laravel application, simply run
phpunit
on the command line to run your
tests.
テスト定義と実行Defining & Running Tests
テストケースを作成するには、app/tests
ディレクトリーにファイルを作成してください。テストケースはTestCase
を拡張してください。PHPUnitを使用する時と同様にテストメソッドを定義します。To create a test case, simply
create a new test file in the app/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 ownsetUp
method, 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.
テストからルートを呼び出す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, $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', array('user' => 1));
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');
**注意:**テスト中の
testing
環境では、ルートフィルターは無効になっています。有効にするには、Route::enableFilters()
をテストで使用してください。Note: Route filters are disabled when in the testing environment. To enable them, addRoute::enableFilters()
to your test.
DOMクローラーDOM Crawler
コンテンツの内容を調べるために、ルートを呼び出し、DOMクローラー(Crawler)インスタンスを受け取ることも可能です。You may also call a route and receive a DOM Crawler instance that you may use to inspect the content:
$crawler = $this->client->request('GET', '/');
$this->assertTrue($this->client->getResponse()->isOk());
$this->assertCount(1, $crawler->filter('h1:contains("Hello World!")'));
どのようにこのクローラーを使用するかをもっと詳しく知りたい場合は公式ドキュメントを参照してください。For more information on how to use the crawler, refer to its official documentation[http://symfony.com/doc/master/components/dom_crawler.html].
FacadesのモックMocking Facades
テストをしているとLaravelのstaticなfacadeの呼び出しのモックが必要となることが多いでしょう。例えば、次のコントローラーアクションを考えてみてください。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', array('name' => 'Dayle'));
return 'All done!';
}
Facadeに対し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.
FacadeをモックするMocking A Facade
public function testGetIndex()
{
Event::shouldReceive('fire')->once()->with('foo', array('name' => 'Dayle'));
$this->call('GET', '/');
}
注意:
Request
Facadeに対してモックは使わないでください。その代わりにテストを実行する場合は、call
メソッドに希望する入力を渡してください。Note: You should not mock theRequest
facade. Instead, pass the input you desire into thecall
method 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(array('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(array('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');
シードの作成についてはドキュメントのマイグレーションとシードの章をご覧ください。More information on creating seeds may be found in the migrations and seeding[/docs/4.2/migrations#database-seeding] section of the documentation.
アプリケーションのリフレッシュRefreshing The Application
ご存知の通り、Laravelのアプリケーション、つまりIoCコンテナへは、テストメソッドの中から$this->app
により、いつでもアクセスできます。このアプリケーションインスタンスは、それぞれのテストクラスごとにリフレッシュされます。特定のメソッドでアプリケーションを強制的に手動リフレッシュしたい場合は、refreshApplication
メソッドをテストメソッドで使用して下さい。これにより、テストケースが実行されることによりIoCコンテナに追加されたモックのような追加結合をリセットします。As you may already know, you can
access your Laravel Application
/ IoC
Container via $this->app
from any
test method. This Application 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.