0
0
Laravelframework~5 mins

HTTP test assertions in Laravel

Choose your learning style9 modes available
Introduction

HTTP test assertions help you check if your web app responds correctly to requests. They make sure your app works as expected without opening a browser.

When you want to confirm a page loads successfully after a user visits it.
When you need to check if submitting a form redirects to the right page.
When you want to verify that an API returns the correct status code and data.
When you want to ensure unauthorized users get blocked from certain pages.
When you want to test that error pages show up correctly for bad requests.
Syntax
Laravel
$response->assertStatus(200);
$response->assertSee('Welcome');
$response->assertRedirect('/home');

Use $response from your HTTP test calls like $this->get() or $this->post().

Assertions check things like status codes, page content, redirects, and JSON responses.

Examples
Check that the home page loads with a 200 OK status.
Laravel
$response = $this->get('/');
$response->assertStatus(200);
Check that after login, the user is redirected to the dashboard.
Laravel
$response = $this->post('/login', ['email' => 'user@example.com', 'password' => 'secret']);
$response->assertRedirect('/dashboard');
Check that the profile page contains the text 'User Profile'.
Laravel
$response = $this->get('/profile');
$response->assertSee('User Profile');
Check that the API returns JSON with a success key set to true.
Laravel
$response = $this->getJson('/api/data');
$response->assertJson(['success' => true]);
Sample Program

This test class has two tests: one checks the home page loads with status 200 and shows a welcome message. The other checks that logging in redirects the user to the dashboard page.

Laravel
<?php

namespace Tests\Feature;

use Tests\TestCase;

class HomePageTest extends TestCase
{
    public function test_home_page_loads_successfully()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
        $response->assertSee('Welcome to Our Site');
    }

    public function test_login_redirects_to_dashboard()
    {
        $response = $this->post('/login', [
            'email' => 'user@example.com',
            'password' => 'password123',
        ]);

        $response->assertRedirect('/dashboard');
    }
}
OutputSuccess
Important Notes

Always use HTTP test assertions inside your test methods after making a request.

Use assertStatus() to check HTTP codes like 200, 404, or 302.

Use assertSee() to check if certain text appears in the response body.

Summary

HTTP test assertions help confirm your app responds correctly to requests.

Common assertions include checking status codes, redirects, and page content.

They make your tests reliable and your app more stable.