HTTP test
- Custom request header
- Testing JSON APIs
- Testing File Upload
- Available Assertion Methods
- Response Assertion
##
Introduction
Laravel provides a very fluent API for both the generation of HTTP requests and the inspection of output. For example, you can look at this test case below: The
<?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
method creates a GET
request to your application, and assertStatus
Method asserts that the response returned is the specified HTTP status code. In addition to this simple assertion, Laravel also includes various assertions that check response headers, content, JSON, structure, etc.
Custom request headers
You can use the withHeaders
method before sending to the application Headers from previous custom requests. You can add any custom headers you want.
<?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, ]); } }
{tip} The CSRF middleware is automatically disabled when running tests.
Session / Authentication
Laravel provides several auxiliaries that can be used during HTTP testing. function. First, you need to pass an array to the withSession
method to set the Session data. This makes it simple for you to load the Session with data before sending the test request of the application:
<?php class ExampleTest extends TestCase{ public function testApplication() { $response = $this->withSession(['foo' => 'bar']) ->get('/'); } }
Of course, Session is generally used to maintain user status, such as authenticating users. actingAs
Helper functions provide an easy way to specify a user to authenticate to for the current user. For example, we can use the factory model to generate and authenticate users:
<?php use App\User; class ExampleTest extends TestCase{ public function testApplication() { $user = factory(User::class)->create(); $response = $this->actingAs($user) ->withSession(['foo' => 'bar']) ->get('/'); } }
You can also specify which guard the user is authenticated through by passing the guard name as the second argument to actingAs
:
$this->actingAs($user, 'api')
Testing JSON APIs
Laravel also provides several helper functions to test JSON APIs and their response. For example, json
, get
, post
, put
, patch
, and delete
Can be used to send various HTTP actions. You can also easily pass data and request headers into these methods. Let's start using them by writing a POST
request to /user
and asserting that the expected data is returned:
<?php class ExampleTest extends TestCase{ /** * 一个简单的功能测试用例。 * * @return void */ public function testBasicExample() { $response = $this->json('POST', '/user', ['name' => 'Sally']); $response ->assertStatus(201) ->assertJson([ 'created' => true, ]); } }
{tip}
assertJson
Method converts the response to an array and utilizesPHPUnit::assertArraySubset
to verify that the given array is present in the JSON response returned by the application. So, if there are other attributes in the JSON response, the test will still pass given the presence of the array:
Verifying an exact match
If you want to verify that a given array exactly matches the JSON result 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, ]); } }
Test file upload
Illuminate\Http\UploadedFile
Provides a fake
method to generate virtual files or images for testing purposes. It can be combined with the fake
method of the Storage
facade to greatly simplify file upload testing. For example, you can combine the two functions to test the avatar upload form very conveniently:
<?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'); } }
Virtual file preparation
In usefake
When creating a file, you can specify the width, height and size of the image to better verify the test rules:
UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);
In addition to creating images, you can also use the create
method to create Other types of files:
UploadedFile::fake()->create('document.pdf', $sizeInKilobytes);
Available assertions
Response Assertion
Laravel provides a variety of common assertion methods for PHPUnit testing. These assertions are accessible from the json
, get
, post
, put
, and delete
test methods:
assertCookie
assertCookieExpired
assertCookieNotExpired
assertCookieMissing
assertDontSee
assertDontSeeText
assertExactJson
assertForbidden
assertHeader
assertHeaderMissing
assertJson
assertJsonCount
assertJsonFragment
assertJsonMissing
assertJsonMissingExact
assertJsonMissingValidationErrors
assertJsonStructure
assertJsonValidationErrors
assertLocation
assertNotFound
assertOk
assertPlainCookie
assertRedirect
assertSee
assertSeeInOrder
assertSeeText
assertSeeTextInOrder
assertSessionHas
assertSessionHasAll
assertSessionHasErrors
assertSessionHasErrorsIn
assertSessionHasNoErrors
assertSessionDoesntHaveErrors
assertSessionMissing
assertStatus
assertSuccessful
assertViewHas
assertViewHasAll
assertViewIs
assertViewMissing
assertCookie
Assert that the given cookie is included in the response:
$response->assertCookie($cookieName, $value = null);
assertCookieExpired
Assert that the given cookie was included in the response and that it has expired:
$response->assertCookieExpired($cookieName);
assertCookieNotExpired
Assert that the given cookie was included in the response and that it has not expired:
$response->assertCookieNotExpired($cookieName);##assertCookieMissingAssert that the given cookie is not included in the response:
$response->assertCookieMissing($cookieName);
Assert that the given cookie is not included in the response A given string:
$response->assertDontSee($value);
Assert that the given string is not contained in the response text:
$response->assertDontSeeText($value);
Assert that the data contained in the response exactly matches the given JSON data:
$response->assertExactJson(array $data);##assertForbiddenAssert that there is a forbidden status code in the response:
$response->assertForbidden();
assertHeaderAssert that the given header is present in the response: $response->assertHeader($headerName, $value = null);
assertHeaderMissingAssert that the given header is not present in the response: $response->assertHeaderMissing($headerName);
$response->assertJson(array $data);
$response->assertJsonCount($count, $key = null);
$response->assertJsonFragment(array $data);Assert that the response does not contain the given JSON fragment:
$response->assertJsonMissing(array $data);
$response->assertJsonMissingExact(array $data);
assertJsonMissingValidationErrors
Assert response does not have a JSON validation error for the given key:$response->assertJsonMissingValidationErrors($keys);
$response->assertJsonStructure(array $structure);
assertJsonValidationErrors
Assert response to the given JSON validation error with the given key:
$response->assertJsonValidationErrors($keys);
assertLocation
Assert that the response has the given URI value in the Location
header:
$response->assertLocation($uri);
assertNotFound
Assert response has not found status code:
$response->assertNotFound();##assertOkAssert response has 200 status code:
$response->assertOk();assertPlainCookieAssert that the response contains the given cookie (unencrypted):
$response->assertPlainCookie($cookieName, $value = null);
Assert that the response will be redirected to the given URI:
$response->assertRedirect($uri);
Assert that the given string is contained in the response:
$response->assertSee($value);
Assert that the response contains the given string in order:
$response->assertSeeInOrder(array $values);
Assert that the given string is contained in the response text:
$response->assertSeeText($value);##assertSeeTextInOrderAssert that the given string is contained in the response text in order:
$response->assertSeeTextInOrder(array $values);
$response->assertSessionHas($key, $value = null);Assert that the session contains the given value list :
$response->assertSessionHasAll(array $data);
$response->assertSessionHasErrors(array $keys, $format = null, $errorBag = 'default');
$response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null);
$response->assertSessionHasNoErrors();
##assertSessionDoesntHaveErrorsAssert session does not contain the given key error:
$response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default');##assertSessionMissing
Assert session does not contain the given key Fixed key:
$response->assertSessionMissing($key);
assertStatus
Assert that the response has the given status code:
$response->assertStatus($code);##assertSuccessfulAssert that there is a successful status code in the response:
$response->assertSuccessful();
Assert that the response view is a given section Data:
$response->assertViewHas($key, $value = null);##assertViewHasAll Assert that the response view has the given data list:
$response->assertViewHasAll(array $data);
assertViewIsAssert route returns the given view: $response->assertViewIs($value);
assertViewMissingAssert that the response view is missing a piece of bound data: $response->assertViewMissing($key);
Authentication AssertionsLaravel also provides various authentication-related assertions for your PHPUnit
tests:Assertion This user has already been authenticated.
| $this->assertGuest($guard = null); |
Assert that this user is not authenticated.
| $this->assertAuthenticatedAs($user, $guard = null); |
Assert that the given user is authenticated.
| $this->assertCredentials(array $credentials, $guard = null); |
Assert that the given credentials are valid.
| $this->assertInvalidCredentials(array $credentials, $guard = null); |
Assert that the given credentials are invalid.
| This article was first published on the |