イントロダクション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 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.
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 theaction
method. Only specify the portion of the class name that follows theApp\Http\Controllers
namespace.
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 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(['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.