HTTP test


##HTTP Tests

Introduction

##

Introduction

Laravel provides a very fluent API for both the generation of HTTP requests and the inspection of output. For example, you can look at this test case below: The

<?php
    namespace Tests\Feature;
    use Tests\TestCase;
    use Illuminate\Foundation\Testing\RefreshDatabase;
    use Illuminate\Foundation\Testing\WithoutMiddleware;
    class ExampleTest extends TestCase{    
    /**
     * 一个基础的测试用例。
     *
     * @return void
     */   
     public function testBasicTest() 
        {     
           $response = $this->get('/');        
           $response->assertStatus(200);  
         }
      }

get method creates a GET request to your application, and assertStatus Method asserts that the response returned is the specified HTTP status code. In addition to this simple assertion, Laravel also includes various assertions that check response headers, content, JSON, structure, etc.

Custom request headers

You can use the withHeaders method before sending to the application Headers from previous custom requests. You can add any custom headers you want.

<?php
    class ExampleTest extends TestCase{
     /**
     * 一个基础的功能测试用例。
     *
     * @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.

Session / Authentication

Laravel provides several auxiliaries that can be used during HTTP testing. function. First, you need to pass an array to the withSession method to set the Session data. This makes it simple for you to load the Session with data before sending the test request of the application:

<?php
    class ExampleTest extends TestCase{  
      public function testApplication()  
        {     
           $response = $this->withSession(['foo' => 'bar'])              
                      ->get('/'); 
         }
    }

Of course, Session is generally used to maintain user status, such as authenticating users. actingAs Helper functions provide an easy way to specify a user to authenticate to for the current user. For example, we can use the factory model to generate and authenticate users:

<?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 can also specify which guard the user is authenticated through by passing the guard name as the second argument to actingAs :

$this->actingAs($user, 'api')

Testing JSON APIs

Laravel also provides several helper functions to test JSON APIs and their response. For example, json, get, post, put, patch, and delete Can be used to send various HTTP actions. You can also easily pass data and request headers into these methods. Let's start using them by writing a POST request to /user and asserting that the expected data is returned:

<?php
    class ExampleTest extends TestCase{   
     /**
     * 一个简单的功能测试用例。
     *
     * @return void
     */   
     public function testBasicExample() 
        {    
            $response = $this->json('POST', '/user', ['name' => 'Sally']);     
            $response        
                ->assertStatus(201)            
                ->assertJson([         
                       'created' => true,           
                       ]);  
         }
     }

{tip} assertJson Method converts the response to an array and utilizes PHPUnit::assertArraySubset to verify that the given array is present in the JSON response returned by the application. So, if there are other attributes in the JSON response, the test will still pass given the presence of the array:

Verifying an exact match

If you want to verify that a given array exactly matches the JSON result returned by the application, you should use the assertExactJson method:

<?php
    class ExampleTest extends TestCase{   
     /**
     * 一个基本的功能测试用例。
     *
     * @return void
     */  
      public function testBasicExample()  
        {     
           $response = $this->json('POST', '/user', ['name' => 'Sally']);        
           $response         
              ->assertStatus(201)            
              ->assertExactJson([           
                   'created' => true,           
                  ]);  
         }
     }

Test file upload

Illuminate\Http\UploadedFile Provides a fake method to generate virtual files or images for testing purposes. It can be combined with the fake method of the Storage facade to greatly simplify file upload testing. For example, you can combine the two functions to test the avatar upload form very conveniently:

<?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,      
             ]);       
           // 断言文件已经存储 . . .       
           Storage::disk('avatars')->assertExists($file->hashName());      
          // 断言文件不存在 . . .        
          Storage::disk('avatars')->assertMissing('missing.jpg');   
       }
 }

Virtual file preparation

In usefake When creating a file, you can specify the width, height and size of the image to better verify the test rules:

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

In addition to creating images, you can also use the create method to create Other types of files:

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

Available assertions

Response Assertion

Laravel provides a variety of common assertion methods for PHPUnit testing. These assertions are accessible from the json, get, post, put, and delete test methods:

assertCookie

Assert that the given cookie is included in the response:

$response->assertCookie($cookieName, $value = null);

assertCookieExpired

Assert that the given cookie was included in the response and that it has expired:

$response->assertCookieExpired($cookieName);

assertCookieNotExpired

Assert that the given cookie was included in the response and that it has not expired:

$response->assertCookieNotExpired($cookieName);

##assertCookieMissing

Assert that the given cookie is not included in the response:

$response->assertCookieMissing($cookieName);

##assertDontSee

Assert that the given cookie is not included in the response A given string:

$response->assertDontSee($value);

assertDontSeeText

Assert that the given string is not contained in the response text:

$response->assertDontSeeText($value);

assertExactJson

Assert that the data contained in the response exactly matches the given JSON data:

$response->assertExactJson(array $data);

##assertForbidden
Assert that there is a forbidden status code in the response:

$response->assertForbidden();

assertHeader
Assert that the given header is present in the response:

$response->assertHeader($headerName, $value = null);

assertHeaderMissing
Assert that the given header is not present in the response:

$response->assertHeaderMissing($headerName);

##assertJson

Assert that the response contains the given JSON data:
$response->assertJson(array $data);

assertJsonCount

Assert that the response JSON has an array where Expected number of elements containing the given key:
$response->assertJsonCount($count, $key = null);

assertJsonFragment

Assert that the response contains the given JSON fragment:
$response->assertJsonFragment(array $data);

##assertJsonMissing

Assert that the response does not contain the given JSON fragment:
$response->assertJsonMissing(array $data);

assertJsonMissingExact

Assert that the response does not contain the exact JSON fragment:
$response->assertJsonMissingExact(array $data);

assertJsonMissingValidationErrors

Assert response does not have a JSON validation error for the given key:
$response->assertJsonMissingValidationErrors($keys);

assertJsonStructure

Assert that the response has the given JSON structure:
$response->assertJsonStructure(array $structure);

assertJsonValidationErrors

Assert response to the given JSON validation error with the given key:

$response->assertJsonValidationErrors($keys);

assertLocation

Assert that the response has the given URI value in the Location header:

$response->assertLocation($uri);

assertNotFound

Assert response has not found status code:

$response->assertNotFound();

##assertOk

Assert response has 200 status code:

$response->assertOk();

assertPlainCookie

Assert that the response contains the given cookie (unencrypted):

$response->assertPlainCookie($cookieName, $value = null);

##assertRedirect

Assert that the response will be redirected to the given URI:

$response->assertRedirect($uri);

assertSee

Assert that the given string is contained in the response:

$response->assertSee($value);

assertSeeInOrder

Assert that the response contains the given string in order:

$response->assertSeeInOrder(array $values);

assertSeeText

Assert that the given string is contained in the response text:

$response->assertSeeText($value);

##assertSeeTextInOrder
Assert that the given string is contained in the response text in order:

$response->assertSeeTextInOrder(array $values);

##assertSessionHas

Assert that the session contains the given data:
$response->assertSessionHas($key, $value = null);

##assertSessionHasAll

Assert that the session contains the given value list :
$response->assertSessionHasAll(array $data);

assertSessionHasErrors

Assert that the session contains an error for a given field:
$response->assertSessionHasErrors(array $keys, $format = null, $errorBag = 'default');

assertSessionHasErrorsIn

Assert that the session has the given errors:
$response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null);

assertSessionHasNoErrors

Assert that the session has no errors:
$response->assertSessionHasNoErrors();

##assertSessionDoesntHaveErrorsAssert session does not contain the given key error:

$response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default');

##assertSessionMissing

Assert session does not contain the given key Fixed key:

$response->assertSessionMissing($key);

assertStatus

Assert that the response has the given status code:

$response->assertStatus($code);

##assertSuccessful

Assert that there is a successful status code in the response:

$response->assertSuccessful();

##assertViewHas

Assert that the response view is a given section Data:

$response->assertViewHas($key, $value = null);

##assertViewHasAll
Assert that the response view has the given data list:

$response->assertViewHasAll(array $data);

assertViewIs
Assert route returns the given view:

$response->assertViewIs($value);

assertViewMissing
Assert that the response view is missing a piece of bound data:

$response->assertViewMissing($key);

Authentication Assertions
Laravel also provides various authentication-related assertions for your

PHPUnit

tests:

MethodDescription##$this->assertAuthenticated($guard = null);$this->assertGuest($guard = null);$this->assertAuthenticatedAs($user, $guard = null);$this->assertCredentials(array $credentials, $guard = null);$this->assertInvalidCredentials(array $credentials, $guard = null);This article was first published on the LearnKu.com website.
Assertion This user has already been authenticated.
Assert that this user is not authenticated.
Assert that the given user is authenticated.
Assert that the given credentials are valid.
Assert that the given credentials are invalid.