HTTP Tests

Introduction

Laravel provides a very fluent API for making HTTP requests to your application and examining the output. For example, take a look at the feature test defined below:

  1. <?php
  2. namespace Tests\Feature;
  3. use Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Foundation\Testing\WithoutMiddleware;
  5. use Tests\TestCase;
  6. class ExampleTest extends TestCase
  7. {
  8. /**
  9. * A basic test example.
  10. *
  11. * @return void
  12. */
  13. public function testBasicTest()
  14. {
  15. $response = $this->get('/');
  16. $response->assertStatus(200);
  17. }
  18. }

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

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:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. /**
  5. * A basic functional test example.
  6. *
  7. * @return void
  8. */
  9. public function testBasicExample()
  10. {
  11. $response = $this->withHeaders([
  12. 'X-Header' => 'Value',
  13. ])->json('POST', '/user', ['name' => 'Sally']);
  14. $response
  15. ->assertStatus(201)
  16. ->assertJson([
  17. 'created' => true,
  18. ]);
  19. }
  20. }

{tip} The CSRF middleware is automatically disabled when running tests.

Cookies

You may use the withCookie or withCookies methods to set cookie values before making a request. The withCookie method accepts a cookie name and value as its two arguments, while the withCookies method accepts an array of name / value pairs:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. public function testCookies()
  5. {
  6. $response = $this->withCookie('color', 'blue')->get('/');
  7. $response = $this->withCookies([
  8. 'color' => 'blue',
  9. 'name' => 'Taylor',
  10. ])->get('/');
  11. }
  12. }

Debugging Responses

After making a test request to your application, the dump, dumpHeaders, and dumpSession methods may be used to examine and debug the response contents:

  1. <?php
  2. namespace Tests\Feature;
  3. use Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Foundation\Testing\WithoutMiddleware;
  5. use Tests\TestCase;
  6. class ExampleTest extends TestCase
  7. {
  8. /**
  9. * A basic test example.
  10. *
  11. * @return void
  12. */
  13. public function testBasicTest()
  14. {
  15. $response = $this->get('/');
  16. $response->dumpHeaders();
  17. $response->dumpSession();
  18. $response->dump();
  19. }
  20. }

Session / Authentication

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:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. public function testApplication()
  5. {
  6. $response = $this->withSession(['foo' => 'bar'])
  7. ->get('/');
  8. }
  9. }

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 to generate and authenticate a user:

  1. <?php
  2. use App\User;
  3. class ExampleTest extends TestCase
  4. {
  5. public function testApplication()
  6. {
  7. $user = factory(User::class)->create();
  8. $response = $this->actingAs($user)
  9. ->withSession(['foo' => 'bar'])
  10. ->get('/');
  11. }
  12. }

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:

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

Testing JSON APIs

Laravel also provides several helpers for testing JSON APIs and their responses. For example, the json, getJson, postJson, putJson, patchJson, deleteJson, and optionsJson methods may be used to issue JSON 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:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. /**
  5. * A basic functional test example.
  6. *
  7. * @return void
  8. */
  9. public function testBasicExample()
  10. {
  11. $response = $this->postJson('/user', ['name' => 'Sally']);
  12. $response
  13. ->assertStatus(201)
  14. ->assertJson([
  15. 'created' => true,
  16. ]);
  17. }
  18. }

{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.

In addition, JSON response data may be accessed as array variables on the response:

  1. $this->assertTrue($response['created']);

Verifying An Exact JSON Match

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:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. /**
  5. * A basic functional test example.
  6. *
  7. * @return void
  8. */
  9. public function testBasicExample()
  10. {
  11. $response = $this->json('POST', '/user', ['name' => 'Sally']);
  12. $response
  13. ->assertStatus(201)
  14. ->assertExactJson([
  15. 'created' => true,
  16. ]);
  17. }
  18. }

Verifying JSON Paths

If you would like to verify that the JSON response contains some given data at a specified path, you should use the assertJsonPath method:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. /**
  5. * A basic functional test example.
  6. *
  7. * @return void
  8. */
  9. public function testBasicExample()
  10. {
  11. $response = $this->json('POST', '/user', ['name' => 'Sally']);
  12. $response
  13. ->assertStatus(201)
  14. ->assertJsonPath('team.owner.name', 'foo')
  15. }
  16. }

Testing File Uploads

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:

  1. <?php
  2. namespace Tests\Feature;
  3. use Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Foundation\Testing\WithoutMiddleware;
  5. use Illuminate\Http\UploadedFile;
  6. use Illuminate\Support\Facades\Storage;
  7. use Tests\TestCase;
  8. class ExampleTest extends TestCase
  9. {
  10. public function testAvatarUpload()
  11. {
  12. Storage::fake('avatars');
  13. $file = UploadedFile::fake()->image('avatar.jpg');
  14. $response = $this->json('POST', '/avatar', [
  15. 'avatar' => $file,
  16. ]);
  17. // Assert the file was stored...
  18. Storage::disk('avatars')->assertExists($file->hashName());
  19. // Assert a file does not exist...
  20. Storage::disk('avatars')->assertMissing('missing.jpg');
  21. }
  22. }

Fake File Customization

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:

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

In addition to creating images, you may create files of any other type using the create method:

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

If needed, you may pass a $mimeType argument to the method to explicitly define the MIME type that should be returned by the file:

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

Available Assertions

Response Assertions

Laravel provides a variety of custom assertion methods for your PHPUnit feature tests. These assertions may be accessed on the response that is returned from the json, get, post, put, and delete test methods:

assertCookieassertCookieExpiredassertCookieNotExpiredassertCookieMissingassertCreatedassertDontSeeassertDontSeeTextassertExactJsonassertForbiddenassertHeaderassertHeaderMissingassertJsonassertJsonCountassertJsonFragmentassertJsonMissingassertJsonMissingExactassertJsonMissingValidationErrorsassertJsonPathassertJsonStructureassertJsonValidationErrorsassertLocationassertNoContentassertNotFoundassertOkassertPlainCookieassertRedirectassertSeeassertSeeInOrderassertSeeTextassertSeeTextInOrderassertSessionHasassertSessionHasInputassertSessionHasAllassertSessionHasErrorsassertSessionHasErrorsInassertSessionHasNoErrorsassertSessionDoesntHaveErrorsassertSessionMissingassertStatusassertSuccessfulassertUnauthorizedassertViewHasassertViewHasAllassertViewIsassertViewMissing

assertCookie

Assert that the response contains the given cookie:

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

assertCookieExpired

Assert that the response contains the given cookie and it is expired:

  1. $response->assertCookieExpired($cookieName);

assertCookieNotExpired

Assert that the response contains the given cookie and it is not expired:

  1. $response->assertCookieNotExpired($cookieName);

assertCookieMissing

Assert that the response does not contains the given cookie:

  1. $response->assertCookieMissing($cookieName);

assertCreated

Assert that the response has a 201 status code:

  1. $response->assertCreated();

assertDontSee

Assert that the given string is not contained within the response. This assertion will automatically escape the given string unless you pass a second argument of false:

  1. $response->assertDontSee($value, $escaped = true);

assertDontSeeText

Assert that the given string is not contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of false:

  1. $response->assertDontSeeText($value, $escaped = true);

assertExactJson

Assert that the response contains an exact match of the given JSON data:

  1. $response->assertExactJson(array $data);

assertForbidden

Assert that the response has a forbidden status code:

  1. $response->assertForbidden();

assertHeader

Assert that the given header is present on the response:

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

assertHeaderMissing

Assert that the given header is not present on the response:

  1. $response->assertHeaderMissing($headerName);

assertJson

Assert that the response contains the given JSON data:

  1. $response->assertJson(array $data, $strict = false);

assertJsonCount

Assert that the response JSON has an array with the expected number of items at the given key:

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

assertJsonFragment

Assert that the response contains the given JSON fragment:

  1. $response->assertJsonFragment(array $data);

assertJsonMissing

Assert that the response does not contain the given JSON fragment:

  1. $response->assertJsonMissing(array $data);

assertJsonMissingExact

Assert that the response does not contain the exact JSON fragment:

  1. $response->assertJsonMissingExact(array $data);

assertJsonMissingValidationErrors

Assert that the response has no JSON validation errors for the given keys:

  1. $response->assertJsonMissingValidationErrors($keys);

assertJsonPath

Assert that the response contains the given data at the specified path:

  1. $response->assertJsonPath($path, array $data, $strict = false);

assertJsonStructure

Assert that the response has a given JSON structure:

  1. $response->assertJsonStructure(array $structure);

assertJsonValidationErrors

Assert that the response has the given JSON validation errors:

  1. $response->assertJsonValidationErrors(array $data);

assertLocation

Assert that the response has the given URI value in the Location header:

  1. $response->assertLocation($uri);

assertNoContent

Assert that the response has the given status code and no content.

  1. $response->assertNoContent($status = 204);

assertNotFound

Assert that the response has a not found status code:

  1. $response->assertNotFound();

assertOk

Assert that the response has a 200 status code:

  1. $response->assertOk();

assertPlainCookie

Assert that the response contains the given cookie (unencrypted):

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

assertRedirect

Assert that the response is a redirect to a given URI:

  1. $response->assertRedirect($uri);

assertSee

Assert that the given string is contained within the response. This assertion will automatically escape the given string unless you pass a second argument of false:

  1. $response->assertSee($value, $escaped = true);

assertSeeInOrder

Assert that the given strings are contained in order within the response. This assertion will automatically escape the given strings unless you pass a second argument of false:

  1. $response->assertSeeInOrder(array $values, $escaped = true);

assertSeeText

Assert that the given string is contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of false:

  1. $response->assertSeeText($value, $escaped = true);

assertSeeTextInOrder

Assert that the given strings are contained in order within the response text. This assertion will automatically escape the given strings unless you pass a second argument of false:

  1. $response->assertSeeTextInOrder(array $values, $escaped = true);

assertSessionHas

Assert that the session contains the given piece of data:

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

assertSessionHasInput

Assert that the session has a given value in the flashed input array:

  1. $response->assertSessionHasInput($key, $value = null);

assertSessionHasAll

Assert that the session has a given list of values:

  1. $response->assertSessionHasAll(array $data);

assertSessionHasErrors

Assert that the session contains an error for the given $keys. If $keys is an associative array, assert that the session contains a specific error message (value) for each field (key):

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

assertSessionHasErrorsIn

Assert that the session contains an error for the given $keys, within a specific error bag. If $keys is an associative array, assert that the session contains a specific error message (value) for each field (key), within the error bag:

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

assertSessionHasNoErrors

Assert that the session has no errors:

  1. $response->assertSessionHasNoErrors();

assertSessionDoesntHaveErrors

Assert that the session has no errors for the given keys:

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

assertSessionMissing

Assert that the session does not contain the given key:

  1. $response->assertSessionMissing($key);

assertStatus

Assert that the response has a given code:

  1. $response->assertStatus($code);

assertSuccessful

Assert that the response has a successful (>= 200 and < 300) status code:

  1. $response->assertSuccessful();

assertUnauthorized

Assert that the response has an unauthorized (401) status code:

  1. $response->assertUnauthorized();

assertViewHas

Assert that the response view was given a piece of data:

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

In addition, view data may be accessed as array variables on the response:

  1. $this->assertEquals('Taylor', $response['name']);

assertViewHasAll

Assert that the response view has a given list of data:

  1. $response->assertViewHasAll(array $data);

assertViewIs

Assert that the given view was returned by the route:

  1. $response->assertViewIs($value);

assertViewMissing

Assert that the response view is missing a piece of bound data:

  1. $response->assertViewMissing($key);

Authentication Assertions

Laravel also provides a variety of authentication related assertions for your PHPUnit feature tests:

MethodDescription
$this->assertAuthenticated($guard = null);Assert that the user is authenticated.
$this->assertGuest($guard = null);Assert that the 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.