Laravel Laravel
  • Prologue

    • Release Notes
    • Upgrade Guide
    • Contribution Guide
    • API Documentation
  • Getting Started

    • Installation
    • Configuration
    • Directory Structure
    • Homestead
    • Valet
  • Architecture Concepts

    • Request Lifecycle
    • Service Container
    • Service Providers
    • Facades
    • Contracts
  • The Basics

    • Routing
    • Middleware
    • CSRF Protection
    • Controllers
    • Requests
    • Responses
    • Views
    • Session
    • Validation
    • Errors & Logging
  • Frontend

    • Blade Templates
    • Localization
    • Frontend Scaffolding
    • Compiling Assets
  • Security

    • Authentication
    • API Authentication
    • Authorization
    • Encryption
    • Hashing
    • Password Reset
  • Digging Deeper

    • Artisan Console
    • Broadcasting
    • Cache
    • Collections
    • Events
    • File Storage
    • Helpers
    • Mail
    • Notifications
    • Package Development
    • Queues
    • Task Scheduling
  • Database

    • Getting Started
    • Query Builder
    • Pagination
    • Migrations
    • Seeding
    • Redis
  • Eloquent ORM

    • Getting Started
    • Relationships
    • Collections
    • Mutators
    • Serialization
  • Testing

    • Getting Started
    • HTTP Tests
    • Browser Tests
    • Database
    • Mocking
  • Official Packages

    • Cashier
    • Envoy
    • Passport
    • Scout
    • Socialite
  • Introduction
  • Session / Authentication
  • Testing JSON APIs
    • Verifying Exact Match
  • Testing File Uploads
  • Available Assertions
Icon

WARNING You're browsing the documentation for an old version of Laravel. Consider upgrading your project to Laravel 11.x.

HTTP Tests

  • Introduction
  • Session / Authentication
  • Testing JSON APIs
  • Testing File Uploads
  • Available Assertions

Introduction

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

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

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.

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('/');
    }
}

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:

<?php

use App\User;

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $user = factory(User::class)->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, 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:

<?php

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $response = $this->json('POST', '/user', ['name' => 'Sally']);

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

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.

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 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(200)
            ->assertExactJson([
                'created' => true,
            ]);
    }
}

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 Tests\TestCase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    public function testAvatarUpload()
    {
        Storage::fake('avatars');

        $response = $this->json('POST', '/avatar', [
            'avatar' => UploadedFile::fake()->image('avatar.jpg')
        ]);

        // Assert the file was stored...
        Storage::disk('avatars')->assertExists('avatar.jpg');

        // 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:

UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);

In addition to creating images, you may create files of any other type using the create method:

UploadedFile::fake()->create('document.pdf', $sizeInKilobytes);

Available Assertions

Laravel provides a variety of custom assertion methods for your PHPUnit tests. These assertions may be accessed on the response that is returned from the json, get, post, put, and delete test methods:

Method Description
$response->assertStatus($code); Assert that the response has a given code.
$response->assertRedirect($uri); Assert that the response is a redirect to a given URI.
$response->assertHeader($headerName, $value = null); Assert that the given header is present on the response.
$response->assertCookie($cookieName, $value = null); Assert that the response contains the given cookie.
$response->assertPlainCookie($cookieName, $value = null); Assert that the response contains the given cookie (unencrypted).
$response->assertSessionHas($key, $value = null); Assert that the session contains the given piece of data.
$response->assertSessionHasErrors(array $keys); Assert that the session contains an error for the given field.
$response->assertSessionMissing($key); Assert that the session does not contain the given key.
$response->assertJson(array $data); Assert that the response contains the given JSON data.
$response->assertJsonFragment(array $data); Assert that the response contains the given JSON fragment.
$response->assertJsonMissing(array $data); Assert that the response does not contain the given JSON fragment.
$response->assertExactJson(array $data); Assert that the response contains an exact match of the given JSON data.
$response->assertJsonStructure(array $structure); Assert that the response has a given JSON structure.
$response->assertViewIs($value); Assert that the given view was returned by the route.
$response->assertViewHas($key, $value = null); Assert that the response view was given a piece of data.
last update:2020-03-12 12:59

成为Laravel合作伙伴

Laravel Partners是提供一流Laravel开发和咨询服务的精英商店。我们每个合作伙伴都可以帮助您制定一个精美,结构完善的项目.

我们的伙伴
Laravel
亮点
  • Our Team
  • 发布说明
  • 入门
  • 路由
  • Blade 模板
  • 身份验证
  • 用户授权
  • Artisan 控制台
  • 数据库
  • Eloquent ORM
  • 测试
资源
  • Laravel Bootcamp
  • Laracasts
  • Laravel News
  • Laracon
  • Laracon EU
  • Laracon India
  • Jobs
  • Forums
  • Trademark
  • 版本发布时间
  • 包开发
  • 命令行应用
  • TALL stack全栈开发
  • Blade UI Kit
  • 前端资源构建
伙伴
  • WebReinvent
  • Vehikl
  • Tighten
  • 64 Robots
  • Active Logic
  • Byte 5
  • Curotec
  • Cyber-Duck
  • DevSquad
  • Jump24
  • Kirschbaum
生态系统
  • Cashier
  • Dusk
  • Echo
  • Envoyer
  • Forge
  • Horizon
  • Nova
  • Octane
  • Sail
  • Sanctum
  • Scout
  • Spark
  • Telescope
  • Valet
  • Vapor

Laravel是一个具有表达力,优雅语法的Web应用程序框架。我们认为,发展必须是一种令人愉悦的创造力,才能真正实现。Laravel试图通过减轻大多数Web项目中使用的常见任务来减轻开发的痛苦.

Laravel是Taylor Otwell的商标.
Copyright © 2011-2025 Laravel中文网 LLC.

  • Twitter
  • GitHub
  • Discord
Laravel 全栈开发网 推荐使用阿里云 按Ctrl+D试试