Laravel cung cấp một API rất dễ hiểu để thực hiện các HTTP request đến application của bạn và kiểm tra kết quả. Ví dụ, hãy xem một bài test mẫu được định nghĩa ở dưới đây:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
Phương thức get
tạo một request GET
vào application, trong khi phương thức assertStatus
xác nhận rằng response được trả về có phải có mã trạng thái HTTP đã cho hay không. Ngoài assertion đơn giản này, Laravel còn chứa nhiều assertion khác nhau để kiểm tra các header response, nội dung, cấu trúc JSON, vv...
Bạn có thể sử dụng phương thức withHeaders
để tùy biến các header của request trước khi nó được gửi đến application. Điều này cho phép bạn thêm bất kỳ header nào bạn muốn vào trong 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} CSRF middleware sẽ tự động bị vô hiệu hóa khi chạy test.
Sau khi tạo ra một bài test request cho ứng dụng của bạn, các phương thức dump
và dumpHeaders
có thể được sử dụng để kiểm tra và debug nội dung response:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->dumpHeaders();
$response->dump();
}
}
Laravel cũng cung cấp một số helper để làm việc với session trong quá trình test HTTP. Đầu tiên, bạn có thể set dữ liệu session thành một mảng nhất định bằng phương thức withSession
. Điều này hữu ích để load session với dữ liệu đã có trước, trước khi gửi request cho application của bạn:
<?php
class ExampleTest extends TestCase
{
public function testApplication()
{
$response = $this->withSession(['foo' => 'bar'])
->get('/');
}
}
Cách dùng chủ yếu của session là để duy trì trạng thái người dùng đã được xác thực. Phương thức helper actingAs
sẽ cung cấp một cách đơn giản để xác thực một người dùng. Ví dụ: chúng ta có thể sử dụng một model factory để tạo và xác thực một người dùng:
<?php
use App\User;
class ExampleTest extends TestCase
{
public function testApplication()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->get('/');
}
}
Bạn cũng có thể khai báo guard nào sẽ được sử dụng để xác thực người dùng bằng cách truyền tên guard làm tham số thứ hai cho phương thức actingAs
:
$this->actingAs($user, 'api')
Laravel cũng cung cấp một số helper để kiểm tra API JSON và response của chúng. Ví dụ, các phương thức json
, get
, post
, put
, patch
, delete
, và option
có thể được sử dụng để đưa vào các request với các method HTTP khác nhau. Bạn cũng có thể dễ dàng truyền dữ liệu và các header cho các phương thức này. Để bắt đầu, hãy viết một bài test để thực hiện một request POST
đến /user
và xác nhận rằng dữ liệu mà bạn mong muốn sẽ trả về:
<?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)
->assertJson([
'created' => true,
]);
}
}
{tip} Phương thức
assertJson
sẽ chuyển response thành một mảng và sử dụngPHPUnit::assertArraySubset
để kiểm tra mảng đó có tồn tại trong response JSON mà được application trả về hay không. Vì vậy, nếu có các thuộc tính khác trong response JSON, bài test này vẫn sẽ được pass miễn là có đoạn đã cho.
Nếu bạn muốn kiểm tra một mảng đã cho là giống chính xác với một response JSON mà được application trả về, bạn nên sử dụng phương thức assertExactJson
:
<?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,
]);
}
}
Class Illuminate\Http\UploadedFile
cung cấp một phương thức fake
có thể được sử dụng để tạo ra các file giả hoặc hình ảnh giả để test. Nó kết hợp cùng với phương thức fake
của facade Storage
sẽ đơn giản hóa rất nhiều cho việc test các file upload. Ví dụ: bạn có thể kết hợp hai chức năng này để dễ dàng test cho một form upload avatar:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
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');
}
}
Khi tạo file bằng phương thức fake
, bạn có thể khai báo width, height, và size của hình ảnh để test tốt hơn cho các validation của bạn:
UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);
Ngoài việc tạo hình ảnh, bạn có thể tạo ra các file thuộc bất kỳ loại nào khác bằng phương thức create
:
UploadedFile::fake()->create('document.pdf', $sizeInKilobytes);
Laravel cung cấp nhiều phương thức assertion để tùy biến cho các bài test PHPUnit của bạn. Các assertion này có thể được truy cập trên các response được trả về từ các phương thức test json
, get
, post
, put
, và delete
:
assertCookie assertCookieExpired assertCookieNotExpired assertCookieMissing assertDontSee assertDontSeeText assertExactJson assertForbidden assertHeader assertHeaderMissing assertJson assertJsonCount assertJsonFragment assertJsonMissing assertJsonMissingExact assertJsonMissingValidationErrors assertJsonStructure assertJsonValidationErrors assertLocation assertNotFound assertOk assertPlainCookie assertRedirect assertSee assertSeeInOrder assertSeeText assertSeeTextInOrder assertSessionHas assertSessionHasInput assertSessionHasAll assertSessionHasErrors assertSessionHasErrorsIn assertSessionHasNoErrors assertSessionDoesntHaveErrors assertSessionMissing assertStatus assertSuccessful assertUnauthorized assertViewHas assertViewHasAll assertViewIs assertViewMissing
Yêu cầu response phải chứa cookie đã cho:
$response->assertCookie($cookieName, $value = null);
Yêu cầu response phải chứa cookie đã cho và nó đã hết hạn:
$response->assertCookieExpired($cookieName);
Yêu cầu response phải chứa cookie đã cho và nó chưa hết hạn:
$response->assertCookieNotExpired($cookieName);
Yêu cầu response không chứa cookie đã cho:
$response->assertCookieMissing($cookieName);
Yêu cầu chuỗi đã cho không có trong response:
$response->assertDontSee($value);
Yêu cầu chuỗi đã cho không có trong text response:
$response->assertDontSeeText($value);
Yêu cầu response phải chứa kết quả khớp chính xác với dữ liệu JSON đã cho:
$response->assertExactJson(array $data);
Yêu cầu response phải chứa một forbidden status code:
$response->assertForbidden();
Yêu cầu header đã cho phải có trong response:
$response->assertHeader($headerName, $value = null);
Yêu cầu header đã cho không có trong response:
$response->assertHeaderMissing($headerName);
Yêu cầu response phải chứa dữ liệu JSON đã cho:
$response->assertJson(array $data);
Yêu cầu JSON response phải chứa một mảng với số lượng item nhất định trong một key đã cho:
$response->assertJsonCount($count, $key = null);
Yêu cầu response phải chứa đoạn JSON đã cho:
$response->assertJsonFragment(array $data);
Yêu cầu response không chứa đoạn JSON đã cho:
$response->assertJsonMissing(array $data);
Yêu cầu response không chứa chính xác đoạn JSON đã cho:
$response->assertJsonMissingExact(array $data);
Yêu cầu response không chứa các lỗi JSON validation cho các khóa đã cho:
$response->assertJsonMissingValidationErrors($keys);
Yêu cầu response có cấu trúc JSON đã cho:
$response->assertJsonStructure(array $structure);
Yêu cầu JSON response trả về lỗi validation:
$response->assertJsonValidationErrors(array $data);
Yêu cầu response có giá trị URI trong header Location
:
$response->assertLocation($uri);
Yêu cầu response có một not found status code:
$response->assertNotFound();
Yêu cầu response có một status code 200:
$response->assertOk();
Yêu cầu response phải chứa một cookie đã cho (không được mã hóa):
$response->assertPlainCookie($cookieName, $value = null);
Yêu cầu response là một redirect đến một URI đã cho:
$response->assertRedirect($uri);
Yêu cầu chuỗi đã cho có trong response:
$response->assertSee($value);
Yêu cầu các chuỗi đã cho được chứa trong response theo thứ tự:
$response->assertSeeInOrder(array $values);
Yêu cầu chuỗi đã cho có trong text response:
$response->assertSeeText($value);
Yêu cầu các chuỗi đã cho được chứa theo thứ tự trong response text:
$response->assertSeeTextInOrder(array $values);
Yêu cầu session có chứa một phần dữ liệu đã cho:
$response->assertSessionHas($key, $value = null);
Yêu cầu session có chứa một giá trị trong flashed input array:
$response->assertSessionHasInput($key, $value = null);
Yêu cầu session có chứa một mảng các giá trị nhất định:
$response->assertSessionHasAll(array $data);
Yêu cầu session có chứa lỗi của các field đã cho:
$response->assertSessionHasErrors(array $keys, $format = null, $errorBag = 'default');
Yêu cầu session có chứa lỗi đã cho:
$response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null);
Yêu cầu session không chứa lỗi:
$response->assertSessionHasNoErrors();
Yêu cầu session không chứa các lỗi cho các khóa đã cho:
$response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default');
Yêu cầu session không chứa key đã cho:
$response->assertSessionMissing($key);
Yêu cầu response trả về status code đã cho:
$response->assertStatus($code);
Yêu cầu response trả về một status code thành công (200):
$response->assertSuccessful();
Yêu cầu response trả về một status code lỗi không quyền truy cập (401):
$response->assertUnauthorized();
Yêu cầu response view có chứa một phần dữ liệu:
$response->assertViewHas($key, $value = null);
Yêu cầu response view có chứa một mảng dữ liệu nhất định:
$response->assertViewHasAll(array $data);
Yêu cầu view đã cho sẽ được trả về từ một route:
$response->assertViewIs($value);
Yêu cầu response view thiếu một phần dữ liệu bị ràng buộc:
$response->assertViewMissing($key);
Laravel cũng sẽ cung cấp nhiều cách authentication liên quan đến assertion cho các bài test PHPUnit của bạn:
Method | Description |
---|---|
$this->assertAuthenticated($guard = null); |
Yêu cầu user phải được authentication. |
$this->assertGuest($guard = null); |
Yêu cầu user không cần phải được authentication. |
$this->assertAuthenticatedAs($user, $guard = null); |
Yêu cầu user đã cho phải được authentication. |
$this->assertCredentials(array $credentials, $guard = null); |
Yêu cầu thông tin đã cho là hợp lệ. |
$this->assertInvalidCredentials(array $credentials, $guard = null); |
Yêu cầu thông tin đã cho là không hợp lệ. |
entry