Skip to content

HTTP Tests

Nguồn gốc: Bản dịch từ HTTP Tests

Giới thiệu (Introduction)

Laravel cung cấp API rất fluent để tạo HTTP request đến ứng dụng và kiểm tra response:

php
<?php

test('the application returns a successful response', function () {
    $response = $this->get('/');

    $response->assertStatus(200);
});
php
<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_the_application_returns_a_successful_response(): void
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

Tạo Requests (Making Requests)

Dùng các method get, post, put, patch, delete trong test. Chúng không tạo HTTP request thật — mô phỏng nội bộ.

php
$response = $this->get('/');
$response->assertStatus(200);

CSRF middleware tự động bị tắt khi chạy test.

Tùy chỉnh Request Headers

php
$response = $this->withHeaders([
    'X-Header' => 'Value',
])->post('/user', ['name' => 'Sally']);

Cookies

php
$response = $this->withCookie('color', 'blue')->get('/');
$response = $this->withCookies([
    'color' => 'blue',
    'name' => 'Taylor',
])->get('/');

Session / Authentication

php
$response = $this->withSession(['banned' => false])->get('/');

Xác thực user:

php
use App\Models\User;

$user = User::factory()->create();

$response = $this->actingAs($user)->get('/');

Debugging Responses

php
$response->dump();
$response->dumpHeaders();
$response->dumpSession();
$response->dd();

Exception Handling

Tắt exception handling để test exception trực tiếp:

php
$this->withoutExceptionHandling();

Testing JSON APIs

php
$response = $this->postJson('/api/user', ['name' => 'Sally']);

$response
    ->assertStatus(201)
    ->assertJson([
        'created' => true,
    ]);

assertExactJson

php
$response->assertExactJson([
    'created' => true,
]);

assertJsonPath

php
$response->assertJsonPath('team.owner.name', 'Dries');

Fluent JSON Testing

php
$response->assertJson(fn (AssertableJson $json) =>
    $json->where('id', 1)
         ->where('name', 'Victoria Faith')
         ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com'))
         ->whereNot('status', 'pending')
         ->missing('password')
         ->etc()
);

Testing File Uploads

php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

Storage::fake('avatars');

$file = UploadedFile::fake()->image('avatar.jpg');

$response = $this->post('/avatar', [
    'avatar' => $file,
]);

Storage::disk('avatars')->assertExists($file->hashName());

Testing Views

php
$response = $this->get('/welcome');

$response->assertViewIs('welcome');
$response->assertViewHas('name', 'Taylor');

Rendering Blade & Components

Render Blade component trực tiếp trong test.

Available Assertions

Response Assertions

MethodMô tả
assertStatus($code)Response có status code cụ thể
assertOk()Status 200
assertCreated()Status 201
assertNoContent()Status 204
assertNotFound()Status 404
assertForbidden()Status 403
assertUnauthorized()Status 401
assertRedirect($uri)Response redirect đến URI
assertHeader($name, $value)Header tồn tại với giá trị
assertCookie($name, $value)Cookie tồn tại
assertJson($data)Response chứa JSON data
assertJsonCount($count)Số phần tử JSON
assertJsonStructure($structure)Cấu trúc JSON
assertSee($value)Response chứa string
assertDontSee($value)Response không chứa string
assertViewIs($name)View trả về đúng tên
assertViewHas($key)View có data key
assertSessionHas($key)Session chứa key

Authentication Assertions

MethodMô tả
assertAuthenticated()User đã xác thực
assertGuest()User chưa xác thực

Validation Assertions

MethodMô tả
assertValid($keys)Không có validation errors cho keys
assertInvalid($keys)Có validation errors cho keys