Application Testing

Introduction

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

  1. <?php
  2. use Illuminate\Foundation\Testing\WithoutMiddleware;
  3. use Illuminate\Foundation\Testing\DatabaseTransactions;
  4. class ExampleTest extends TestCase
  5. {
  6. /**
  7. * A basic functional test example.
  8. *
  9. * @return void
  10. */
  11. public function testBasicExample()
  12. {
  13. $this->visit('/')
  14. ->see('Laravel 5')
  15. ->dontSee('Rails');
  16. }
  17. }

The visit method makes a GET request into the application. The see method asserts that we should see the given text in the response returned by the application. The dontSee method asserts that the given text is not returned in the application response. This is the most basic application test available in Laravel.

You may also use the 'visitRoute' method to make a 'GET' request via a named route:

  1. $this->visitRoute('profile');
  2. $this->visitRoute('profile', ['user' => 1]);

Interacting With Your Application

Of course, you can do much more than simply assert that text appears in a given response. Let's take a look at some examples of clicking links and filling out forms:

In this test, we will make a request to the application, "click" a link in the returned response, and then assert that we landed on a given URI. For example, let's assume there is a link in our response that has a text value of "About Us":

  1. <a href="/about-us">About Us</a>

Now, let's write a test that clicks the link and asserts the user lands on the correct page:

  1. public function testBasicExample()
  2. {
  3. $this->visit('/')
  4. ->click('About Us')
  5. ->seePageIs('/about-us');
  6. }

You may also check that the user has arrived at the correct named route using the seeRouteIs method:

  1. ->seeRouteIs('profile', ['user' => 1]);

Interacting With Forms

Laravel also provides several methods for testing forms. The type, select, check, attach, and press methods allow you to interact with all of your form's inputs. For example, let's imagine this form exists on the application's registration page:

  1. <form action="/register" method="POST">
  2. {{ csrf_field() }}
  3. <div>
  4. Name: <input type="text" name="name">
  5. </div>
  6. <div>
  7. <input type="checkbox" value="yes" name="terms"> Accept Terms
  8. </div>
  9. <div>
  10. <input type="submit" value="Register">
  11. </div>
  12. </form>

We can write a test to complete this form and inspect the result:

  1. public function testNewUserRegistration()
  2. {
  3. $this->visit('/register')
  4. ->type('Taylor', 'name')
  5. ->check('terms')
  6. ->press('Register')
  7. ->seePageIs('/dashboard');
  8. }

Of course, if your form contains other inputs such as radio buttons or drop-down boxes, you may easily fill out those types of fields as well. Here is a list of each form manipulation method:

MethodDescription
$this->type($text, $elementName)"Type" text into a given field.
$this->select($value, $elementName)"Select" a radio button or drop-down field.
$this->check($elementName)"Check" a checkbox field.
$this->uncheck($elementName)"Uncheck" a checkbox field.
$this->attach($pathToFile, $elementName)"Attach" a file to the form.
$this->press($buttonTextOrElementName)"Press" a button with the given text or name.

File Inputs

If your form contains file inputs, you may attach files to the form using the attach method:

  1. public function testPhotoCanBeUploaded()
  2. {
  3. $this->visit('/upload')
  4. ->attach($pathToFile, 'photo')
  5. ->press('Upload')
  6. ->see('Upload Successful!');
  7. }

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. $this->json('POST', '/user', ['name' => 'Sally'])
  12. ->seeJson([
  13. 'created' => true,
  14. ]);
  15. }
  16. }

{tip} The seeJson method converts the given array into JSON, and then verifies that the JSON fragment occurs anywhere within the entire 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 seeJsonEquals 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. $this->json('POST', '/user', ['name' => 'Sally'])
  12. ->seeJsonEquals([
  13. 'created' => true,
  14. ]);
  15. }
  16. }

Verifying Structural Match

It is also possible to verify that a JSON response adheres to a specific structure. In this scenario, you should use the seeJsonStructure method and pass it your expected JSON structure:

  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. $this->get('/user/1')
  12. ->seeJsonStructure([
  13. 'name',
  14. 'pet' => [
  15. 'name', 'age'
  16. ]
  17. ]);
  18. }
  19. }

The above example illustrates an expectation of receiving a name attribute and a nested pet object with its own name and age attributes. seeJsonStructure will not fail if additional keys are present in the response. For example, the test would still pass if the pet had a weight attribute.

You may use the * to assert that the returned JSON structure has a list where each list item contains at least the attributes found in the set of values:

  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. // Assert that each user in the list has at least an id, name and email attribute.
  12. $this->get('/users')
  13. ->seeJsonStructure([
  14. '*' => [
  15. 'id', 'name', 'email'
  16. ]
  17. ]);
  18. }
  19. }

You may also nest the * notation. In this case, we will assert that each user in the JSON response contains a given set of attributes and that each pet on each user also contains a given set of attributes:

  1. $this->get('/users')
  2. ->seeJsonStructure([
  3. '*' => [
  4. 'id', 'name', 'email', 'pets' => [
  5. '*' => [
  6. 'name', 'age'
  7. ]
  8. ]
  9. ]
  10. ]);

Sessions / Authentication

Laravel provides several helpers for working with the session during 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. $this->withSession(['foo' => 'bar'])
  7. ->visit('/');
  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. class ExampleTest extends TestCase
  3. {
  4. public function testApplication()
  5. {
  6. $user = factory(App\User::class)->create();
  7. $this->actingAs($user)
  8. ->withSession(['foo' => 'bar'])
  9. ->visit('/')
  10. ->see('Hello, '.$user->name);
  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')

Disabling Middleware

When testing your application, you may find it convenient to disable middleware for some of your tests. This will allow you to test your routes and controller in isolation from any middleware concerns. Laravel includes a simple WithoutMiddleware trait that you can use to automatically disable all middleware for the test class:

  1. <?php
  2. use Illuminate\Foundation\Testing\WithoutMiddleware;
  3. use Illuminate\Foundation\Testing\DatabaseMigrations;
  4. use Illuminate\Foundation\Testing\DatabaseTransactions;
  5. class ExampleTest extends TestCase
  6. {
  7. use WithoutMiddleware;
  8. //
  9. }

If you would like to only disable middleware for a few test methods, you may call the withoutMiddleware method from within the test methods:

  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. $this->withoutMiddleware();
  12. $this->visit('/')
  13. ->see('Laravel 5');
  14. }
  15. }

Custom HTTP Requests

If you would like to make a custom HTTP request into your application and get the full Illuminate\Http\Response object, you may use the call method:

  1. public function testApplication()
  2. {
  3. $response = $this->call('GET', '/');
  4. $this->assertEquals(200, $response->status());
  5. }

If you are making POST, PUT, or PATCH requests you may pass an array of input data with the request. Of course, this data will be available in your routes and controller via the Request instance:

  1. $response = $this->call('POST', '/user', ['name' => 'Taylor']);

PHPUnit Assertions

Laravel provides a variety of custom assertion methods for PHPUnit tests:

MethodDescription
->assertResponseOk();Assert that the client response has an OK status code.
->assertResponseStatus($code);Assert that the client response has a given code.
->assertViewHas($key, $value = null);Assert that the response view has a given piece of bound data.
->assertViewHasAll(array $bindings);Assert that the view has a given list of bound data.
->assertViewMissing($key);Assert that the response view is missing a piece of bound data.
->assertRedirectedTo($uri, $with = []);Assert whether the client was redirected to a given URI.
->assertRedirectedToRoute($name, $parameters = [], $with = []);Assert whether the client was redirected to a given route.
->assertRedirectedToAction($name, $parameters = [], $with = []);Assert whether the client was redirected to a given action.
->assertSessionHas($key, $value = null);Assert that the session has a given value.
->assertSessionHasAll(array $bindings);Assert that the session has a given list of values.
->assertSessionHasErrors($bindings = [], $format = null);Assert that the session has errors bound.
->assertHasOldInput();Assert that the session has old input.
->assertSessionMissing($key);Assert that the session is missing a given key.