samedi 17 avril 2021

How to run setUp function once per class in Laravel 8 tests?

I would like to run the setUP function just once in a class so all the tests can use the same information since it is read only.

Example: I have my API and in a class I want to test an enpoint that requires an authentication token.For obtaining the authentication token I need to create a user, make the login, and save the token so it can be used to test the endpoint. Right now with the setUp funciton the user is created for each test it would be enough to do it once and share the same token among all the tests. Additionally I am using the RefreshDatabase trait to keep the database clean but I want it as well to run only once per class.

Here I leave a sample code. createUser and loginUser are not implemented here.

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use Tests\TestUtils;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    const  TEST_ENDPOINT = '/myendpoint';

    private string $token;

    public function setUp(): void
    {
        createUser();
        $this->token = loginUser(); //runs for every test
    }

    public function test_endpoint_INVALID_AUTHORIZATION()
    {
        $response = $this->post(self::TEST_ENDPOINT);
        $response->assertStatus(400);
    }

    /*

    ... other tests

    */

    public function test_endpoint_SUCCESS()
    {
        $headers = TestUtils::createHeadersWithBearerToken($this->token);
        $response = $this->withHeaders($headers)
                        ->post(self::TEST_ENDPOINT);
        $response->assertStatus(200);
    }
}

Aucun commentaire:

Enregistrer un commentaire