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 test defined below:

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

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.

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

Of course, 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, 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:

  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(200)
  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.

Verifying Exact 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(200)
  14. ->assertExactJson([
  15. 'created' => true,
  16. ]);
  17. }
  18. }

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 Tests\TestCase;
  4. use Illuminate\Http\UploadedFile;
  5. use Illuminate\Support\Facades\Storage;
  6. use Illuminate\Foundation\Testing\WithoutMiddleware;
  7. use Illuminate\Foundation\Testing\DatabaseMigrations;
  8. use Illuminate\Foundation\Testing\DatabaseTransactions;
  9. class ExampleTest extends TestCase
  10. {
  11. public function testAvatarUpload()
  12. {
  13. Storage::fake('avatars');
  14. $response = $this->json('POST', '/avatar', [
  15. 'avatar' => UploadedFile::fake()->image('avatar.jpg')
  16. ]);
  17. // Assert the file was stored...
  18. Storage::disk('avatars')->assertExists('avatar.jpg');
  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);

Available Assertions

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

MethodDescription
$response->assertStatus($code);Assert that the response has a given code.
$response->assertRedirect($uri);Assert that the response is a redirect to a given URI.
$response->assertHeader($headerName, $value = null);Assert that the given header is present on the response.
$response->assertCookie($cookieName, $value = null);Assert that the response contains the given cookie.
$response->assertPlainCookie($cookieName, $value = null);Assert that the response contains the given cookie (unencrypted).
$response->assertSessionHas($key, $value = null);Assert that the session contains the given piece of data.
$response->assertSessionHasErrors(array $keys);Assert that the session contains an error for the given field.
$response->assertSessionMissing($key);Assert that the session does not contain the given key.
$response->assertJson(array $data);Assert that the response contains the given JSON data.
$response->assertJsonFragment(array $data);Assert that the response contains the given JSON fragment.
$response->assertJsonMissing(array $data);Assert that the response does not contain the given JSON fragment.
$response->assertExactJson(array $data);Assert that the response contains an exact match of the given JSON data.
$response->assertJsonStructure(array $structure);Assert that the response has a given JSON structure.
$response->assertViewIs($value);Assert that the given view was returned by the route.
$response->assertViewHas($key, $value = null);Assert that the response view was given a piece of data.