Readouble

Laravel 5.7 HTTPテスト

イントロダクションIntroduction

Laravelはアプリケーションに対するHTTPリクエストを作成し、出力を検査するためのとても記述的なAPIを用意しています。例として、以下のテストをご覧ください。Laravel provides a very fluent API for making HTTP requests to your application and examining the output. For example, take a look at the test defined below:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

getメソッドはアプリケーションに対して、GETリクエストを作成します。assertStatusメソッドは返されたレスポンスが指定したHTTPステータスコードを持っていることをアサートします。このシンプルな例に加え、レスポンスヘッダ、コンテンツ、JSON構造などを検査する様々なアサートをLaravelは用意しています。The get method makes a GET request into the application, while the assertStatus method asserts that the returned response should have the given HTTP status code. In addition to this simple assertion, Laravel also contains a variety of assertions for inspecting the response headers, content, JSON structure, and more.

リクエストヘッダのカスタマイズCustomizing Request Headers

アプリーケーションへ送り返す前に、リクエストヘッダをカスタマイズするには、withHeadersメソッドを使います。これにより任意のカスタムヘッダをリクエストに追加することができます。You may use the withHeaders method to customize the request's headers before it is sent to the application. This allows you to add any custom headers you would like to the request:

<?php

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $response = $this->withHeaders([
            'X-Header' => 'Value',
        ])->json('POST', '/user', ['name' => 'Sally']);

        $response
            ->assertStatus(201)
            ->assertJson([
                'created' => true,
            ]);
    }
}

lightbulb">Tip!! テスト実行時、CSRFミドルウェアは自動的に無効になります。{tip} The CSRF middleware is automatically disabled when running tests.

セッション/認証Session / Authentication

Laravelはテスト時にセッションを操作するたくさんのヘルパも提供しています。1つ目は指定した配列をセッションに保存するwithSessionメソッドです。これはアプリケーションのリクエストをテストする前に、データをセッションにロードしたい場合に便利です。Laravel provides several helpers for working with the session during HTTP testing. First, you may set the session data to a given array using the withSession method. This is useful for loading the session with data before issuing a request to your application:

<?php

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $response = $this->withSession(['foo' => 'bar'])
                         ->get('/');
    }
}

認証済みのユーザーのようなユーザー状態をセッションへ保持するのは一般的です。actingAsヘルパメソッドは現在認証済みのユーザーを指定する簡単な手段を提供します。例として、モデルファクトリでユーザーを生成し、認証してみましょう。One common use of the session is for maintaining state for the authenticated user. The actingAs helper method provides a simple way to authenticate a given user as the current user. For example, we may use a model factory[/docs/{{version}}/database-testing#writing-factories] to generate and authenticate a user:

<?php

use App\User;

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $user = factory(User::class)->create();

        $response = $this->actingAs($user)
                         ->withSession(['foo' => 'bar'])
                         ->get('/');
    }
}

ユーザーの認証にどのガードを使用するかを指定したい場合、actingAsメソッドの第2引数にガード名を渡します。You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the actingAs method:

$this->actingAs($user, 'api')

JSON APIのテストTesting JSON APIs

LaravelはJSON APIとレスポンスをテストする数多くのヘルパを用意しています。たとえば、jsongetpostputpatchdeleteメソッドはそれぞれのHTTP動詞のリクエストを発生させるために使用します。これらのメソッドには簡単にデータやヘッダを渡せます。手始めに、/userに対するPOSTリクエストを作成し、期待したデータが返されることをアサートするテストを書いてみましょう。Laravel also provides several helpers for testing JSON APIs and their responses. For example, the json, get, post, put, patch, and delete methods may be used to issue requests with various HTTP verbs. You may also easily pass data and headers to these methods. To get started, let's write a test to make a POST request to /user and assert that the expected data was returned:

<?php

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $response = $this->json('POST', '/user', ['name' => 'Sally']);

        $response
            ->assertStatus(201)
            ->assertJson([
                'created' => true,
            ]);
    }
}

lightbulb">Tip!! The assertJsonメソッドはレスポンスを配列へ変換し、PHPUnit::assertArraySubsetを使用しアプリケーションへ戻ってきたJSONレスポンスの中に、指定された配列が含まれているかを確認します。そのため、JSONレスポンスの中に他のプロパティが存在していても、このテストは指定した一部が残っている限り、テストはパスし続けます。{tip} The assertJson method converts the response to an array and utilizes PHPUnit::assertArraySubset to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.

JSONとの完全一致を検証Verifying An Exact JSON Match

アプリケーションから返されるJSONが、指定した配列と完全に一致することを検証したい場合は、assertExactJsonメソッドを使用します。If you would like to verify that the given array is an exact match for the JSON returned by the application, you should use the assertExactJson method:

<?php

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $response = $this->json('POST', '/user', ['name' => 'Sally']);

        $response
            ->assertStatus(201)
            ->assertExactJson([
                'created' => true,
            ]);
    }
}

ファイルアップロードのテストTesting File Uploads

Illuminate\Http\UploadedFileクラスは、テストのためにファイルやイメージのダミーを生成するためのfakeメソッドを用意しています。これをStorageファサードのfakeメソッドと組み合わせることで、ファイルアップロードのテストがとてもシンプルになります。例として、2つの機能を組み合わせて、アバターのアップロードをテストしてみましょう。The Illuminate\Http\UploadedFile class provides a fake method which may be used to generate dummy files or images for testing. This, combined with the Storage facade's fake method greatly simplifies the testing of file uploads. For example, you may combine these two features to easily test an avatar upload form:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ExampleTest extends TestCase
{
    public function testAvatarUpload()
    {
        Storage::fake('avatars');

        $file = UploadedFile::fake()->image('avatar.jpg');

        $response = $this->json('POST', '/avatar', [
            'avatar' => $file,
        ]);

        // ファイルが保存されたことをアサートする
        Storage::disk('avatars')->assertExists($file->hashName());

        // ファイルが存在しないことをアサートする
        Storage::disk('avatars')->assertMissing('missing.jpg');
    }
}

ダミーファイルのカスタマイズFake File Customization

fakeメソッドでファイルを生成するときには、バリデーションルールをより便利にテストできるように、画像の幅、高さ、サイズを指定できます。When creating files using the fake method, you may specify the width, height, and size of the image in order to better test your validation rules:

UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);

画像の生成に付け加え、createメソッドで他のタイプのファイルも生成できます。In addition to creating images, you may create files of any other type using the create method:

UploadedFile::fake()->create('document.pdf', $sizeInKilobytes);

利用可能なアサートAvailable Assertions

レスポンスのアサートResponse Assertions

PHPUnitテスト用に、数多くの追加アサートメソッドをLaravelは提供しています。以下のアサートで、jsongetpostputdeleteテストメソッドから返されたレスポンスへアクセスしてください。Laravel provides a variety of custom assertion methods for your PHPUnit[https://phpunit.de/] tests. These assertions may be accessed on the response that is returned from the json, get, post, put, and delete test methods:

assertCookieassertCookie

レスポンスが指定したクッキーを持っていることを宣言。Assert that the response contains the given cookie:

$response->assertCookie($cookieName, $value = null);

assertCookieExpiredassertCookieExpired

レスポンスが指定したクッキーを持っており、期限切れであることを宣言。Assert that the response contains the given cookie and it is expired:

$response->assertCookieExpired($cookieName);

assertCookieNotExpiredassertCookieNotExpired

レスポンスが指定したクッキーを持っており、期限切れでないことを宣言。Assert that the response contains the given cookie and it is not expired:

$response->assertCookieNotExpired($cookieName);

assertCookieMissingassertCookieMissing

レスポンスが指定したクッキーを持っていないことを宣言。Assert that the response does not contains the given cookie:

$response->assertCookieMissing($cookieName);

assertDontSeeassertDontSee

指定した文字列がレスポンスに含まれていないことを宣言。Assert that the given string is not contained within the response:

$response->assertDontSee($value);

assertDontSeeTextassertDontSeeText

指定した文字列がレスポンステキストに含まれていないことを宣言。Assert that the given string is not contained within the response text:

$response->assertDontSeeText($value);

assertExactJsonassertExactJson

レスポンスが指定したJSONデータと完全に一致するデータを持っていることを宣言。Assert that the response contains an exact match of the given JSON data:

$response->assertExactJson(array $data);

assertForbiddenassertForbidden

レスポンスがforbiddenステータスコードを持っていることを宣言。Assert that the response has a forbidden status code:

$response->assertForbidden();

assertHeaderassertHeader

レスポンスに指定したヘッダが存在していることを宣言。Assert that the given header is present on the response:

$response->assertHeader($headerName, $value = null);

assertHeaderMissingassertHeaderMissing

レスポンスに指定したヘッダが存在していないことを宣言。Assert that the given header is not present on the response:

$response->assertHeaderMissing($headerName);

assertJsonassertJson

レスポンスが指定したJSONデータを持っていることを宣言。Assert that the response contains the given JSON data:

$response->assertJson(array $data);

assertJsonCountassertJsonCount

レスポンスJSONが、指定したキーのアイテムを、期待値分持っていることを宣言。Assert that the response JSON has an array with the expected number of items at the given key:

$response->assertJsonCount($count, $key = null);

assertJsonFragmentassertJsonFragment

レスポンスが指定したJSONの一部を含んでいることを宣言。Assert that the response contains the given JSON fragment:

$response->assertJsonFragment(array $data);

assertJsonMissingassertJsonMissing

レスポンスが指定したJSONの一部を含んでいないことを宣言。Assert that the response does not contain the given JSON fragment:

$response->assertJsonMissing(array $data);

assertJsonMissingExactassertJsonMissingExact

レスポンスがJSONの一部をそのまま含んでいないことを宣言。Assert that the response does not contain the exact JSON fragment:

$response->assertJsonMissingExact(array $data);

assertJsonMissingValidationErrorsassertJsonMissingValidationErrors

レスポンスが指定したキーに対するJSONバリデーションエラーを含んていないことを宣言。Assert that the response has no JSON validation errors for the given keys:

$response->assertJsonMissingValidationErrors($keys);

assertJsonStructureassertJsonStructure

レスポンスが指定したJSONの構造を持っていることを宣言。Assert that the response has a given JSON structure:

$response->assertJsonStructure(array $structure);

assertJsonValidationErrorsassertJsonValidationErrors

レスポンスが指定したキーの、指定したJSONバリデーションエラーを持っていることを宣言。Assert that the response has the given JSON validation errors for the given keys:

$response->assertJsonValidationErrors($keys);

assertLocationassertLocation

レスポンスのLocationヘッダが、指定したURIを持つことを宣言。Assert that the response has the given URI value in the Location header:

$response->assertLocation($uri);

assertNotFoundassertNotFound

レスポンスがnot foundのステータスコードを持っていることを宣言。Assert that the response has a not found status code:

$response->assertNotFound();

assertOkassertOk

レスポンスが200のステータスコードを持っていることを宣言。Assert that the response has a 200 status code:

$response->assertOk();

assertPlainCookieassertPlainCookie

レスポンスが指定した暗号化されていないクッキーを持っていることを宣言。Assert that the response contains the given cookie (unencrypted):

$response->assertPlainCookie($cookieName, $value = null);

assertRedirectassertRedirect

クライアントが指定したURIへリダイレクトすることを宣言。Assert that the response is a redirect to a given URI:

$response->assertRedirect($uri);

assertSeeassertSee

指定した文字列がレスポンスに含まれていることを宣言。Assert that the given string is contained within the response:

$response->assertSee($value);

assertSeeInOrderassertSeeInOrder

指定した文字列が、順番通りにレスポンスに含まれていることを宣言。Assert that the given strings are contained in order within the response:

$response->assertSeeInOrder(array $values);

assertSeeTextassertSeeText

指定した文字列がレスポンステキストに含まれていることを宣言。Assert that the given string is contained within the response text:

$response->assertSeeText($value);

assertSeeTextInOrderassertSeeTextInOrder

指定した文字列が、順番通りにレンスポンステキストへ含まれていることを宣言。Assert that the given strings are contained in order within the response text:

$response->assertSeeTextInOrder(array $values);

assertSessionHasassertSessionHas

セッションが指定したデータを持っていることを宣言。Assert that the session contains the given piece of data:

$response->assertSessionHas($key, $value = null);

assertSessionHasAllassertSessionHasAll

セッションが指定したリストの値を持っていることを宣言。Assert that the session has a given list of values:

$response->assertSessionHasAll(array $data);

assertSessionHasErrorsassertSessionHasErrors

セッションが指定したフィールドに対するエラーを含んでいることを宣言。Assert that the session contains an error for the given field:

$response->assertSessionHasErrors(array $keys, $format = null, $errorBag = 'default');

assertSessionHasErrorsInassertSessionHasErrorsIn

セッションが指定したエラーを持っていることを宣言。Assert that the session has the given errors:

$response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null);

assertSessionHasNoErrorsassertSessionHasNoErrors

セッションがエラーを持っていないことを宣言。Assert that the session has no errors:

$response->assertSessionHasNoErrors();

assertSessionDoesntHaveErrorsassertSessionDoesntHaveErrors

セッションが、指定したキーに対するエラーを持っていないことを宣言。Assert that the session has no errors for the given keys:

$response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default');

assertSessionMissingassertSessionMissing

セッションが指定したキーを持っていないことを宣言。Assert that the session does not contain the given key:

$response->assertSessionMissing($key);

assertStatusassertStatus

クライアントのレスポンスが指定したコードであることを宣言。Assert that the response has a given code:

$response->assertStatus($code);

assertSuccessfulassertSuccessful

レスポンスが成功のステータスコードであることを宣言。Assert that the response has a successful status code:

$response->assertSuccessful();

assertViewHasassertViewHas

レスポンスビューが指定したデータを持っていることを宣言。Assert that the response view was given a piece of data:

$response->assertViewHas($key, $value = null);

assertViewHasAllassertViewHasAll

レスポンスビューが指定したリストのデータを持っていることを宣言。Assert that the response view has a given list of data:

$response->assertViewHasAll(array $data);

assertViewIsassertViewIs

ルートにより、指定したビューが返されたことを宣言。Assert that the given view was returned by the route:

$response->assertViewIs($value);

assertViewMissingassertViewMissing

レスポンスビューが指定したデータを持っていないことを宣言。Assert that the response view is missing a piece of bound data:

$response->assertViewMissing($key);

認証のアサートAuthentication Assertions

Laravelは、PHPUnitテストのために認証関連の様々なアサーションも提供しています。Laravel also provides a variety of authentication related assertions for your PHPUnit[https://phpunit.de/] tests:

メソッドMethod 説明Description
$this->assertAuthenticated($guard = null);$this->assertAuthenticated($guard = null); ユーザーが認証されていることを宣言。Assert that the user is authenticated.
$this->assertGuest($guard = null);$this->assertGuest($guard = null); ユーザーが認証されていないことを宣言。Assert that the user is not authenticated.
$this->assertAuthenticatedAs($user, $guard = null);$this->assertAuthenticatedAs($user, $guard = null); 指定したユーザーが認証されていることを宣言。Assert that the given user is authenticated.
$this->assertCredentials(array $credentials, $guard = null);$this->assertCredentials(array $credentials, $guard = null); 指定した認証情報が有効であることを宣言。Assert that the given credentials are valid.
$this->assertInvalidCredentials(array $credentials, $guard = null);$this->assertInvalidCredentials(array $credentials, $guard = null); 指定した認証情報が無効であることを宣言。Assert that the given credentials are invalid.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作