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:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
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:
<?php
class ExampleTest extends TestCase
{
/**
* A basic functional test example.
*
* @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.
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:
<?php
class ExampleTest extends TestCase
{
public function testCookies()
{
$response = $this->withCookie('color', 'blue')->get('/');
$response = $this->withCookies([
'color' => 'blue',
'name' => 'Taylor',
])->get('/');
}
}
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:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->dumpHeaders();
$response->dumpSession();
$response->dump();
}
}
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:
<?php
class ExampleTest extends TestCase
{
public function testApplication()
{
$response = $this->withSession(['foo' => 'bar'])
->get('/');
}
}
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:
<?php
use App\Models\User;
class ExampleTest extends TestCase
{
public function testApplication()
{
$user = User::factory()->create();
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->get('/');
}
}
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')
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:
<?php
class ExampleTest extends TestCase
{
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$response = $this->postJson('/user', ['name' => 'Sally']);
$response
->assertStatus(201)
->assertJson([
'created' => true,
]);
}
}
{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:
$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:
<?php
class ExampleTest extends TestCase
{
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$response = $this->json('POST', '/user', ['name' => 'Sally']);
$response
->assertStatus(201)
->assertExactJson([
'created' => true,
]);
}
}
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:
<?php
class ExampleTest extends TestCase
{
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$response = $this->json('POST', '/user', ['name' => 'Sally']);
$response
->assertStatus(201)
->assertJsonPath('team.owner.name', 'foo');
}
}
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:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function testAvatarUpload()
{
Storage::fake('avatars');
$file = UploadedFile::fake()->image('avatar.jpg');
$response = $this->json('POST', '/avatar', [
'avatar' => $file,
]);
// Assert the file was stored...
Storage::disk('avatars')->assertExists($file->hashName());
// Assert a file does not exist...
Storage::disk('avatars')->assertMissing('missing.jpg');
}
}
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:
Laravel allows you to render a view in isolation without making a simulated HTTP request to the application. To accomplish this, you may use the view method within your test. The view method accepts the view name and an optional array of data. The method returns an instance of Illuminate\Testing\TestView, which offers several methods to conveniently make assertions about the view's contents:
public function testWelcomeView()
{
$view = $this->view('welcome', ['name' => 'Taylor']);
$view->assertSee('Taylor');
}
The TestView object provides the following assertion methods: assertSee, assertSeeInOrder, assertSeeText, assertSeeTextInOrder, assertDontSee, and assertDontSeeText.
If needed, you may get the raw, rendered view contents by casting the TestView instance to a string:
$contents = (string) $this->view('welcome');
Sharing Errors
Some views may depend on errors shared in the global error bag provided by Laravel. To hydrate the error bag with error messages, you may use the withViewErrors method:
$view = $this->withViewErrors([
'name' => ['Please provide a valid name.']
])->view('form');
$view->assertSee('Please provide a valid name.');
Rendering Blade & Components
If necessary, you may use the blade method to evaluate and render a raw Blade string. Like the view method, the blade method returns an instance of Illuminate\Testing\TestView:
You may use the component method to evaluate and render a blade component. Like the view method, the component method returns an instance of Illuminate\Testing\TestView:
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:
Assert that the response contains the given cookie and it is expired:
$response->assertCookieExpired($cookieName);
assertCookieNotExpired
Assert that the response contains the given cookie and it is not expired:
$response->assertCookieNotExpired($cookieName);
assertCookieMissing
Assert that the response does not contains the given cookie:
$response->assertCookieMissing($cookieName);
assertCreated
Assert that the response has a 201 status code:
$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:
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:
Assert that the response is a redirect to a given URI:
$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:
$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:
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:
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:
Assert that the session has a given list of values:
$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):
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: