Y
Y
yarnstart2020-02-18 01:09:04
PHP
yarnstart, 2020-02-18 01:09:04

How to avoid code duplication in phpunit test?

I created a test, three methods testing registration, login, logout (REST API, Laravel Passport), it immediately catches your eye that you have to copy-paste half of the code from testLogin to testLogout, because otherwise, the base at the time of testLogout will not contain the user (passing it through @depends does not make sense), there is an idea to move the user creation and login code into a private method and use it in testLogin and testLogout, I don’t know how correct this is.
Googled about setUp, but it is executed before each method, and this code will not be needed before testRegister.

Sample code:

the code

class AuthTest extends TestCase
{
    use DatabaseMigrations;

    public function testRegister()
    {
        $user = factory(User::class)->make(['password' => 'password123']);

        $route = route('register');
        $payload = [
            'name' => $user->name,
            'email' => $user->email,
            'password' => $user->password,
            'password_confirmation' => $user->password,
        ];

        $this->post($route, $payload)->assertStatus(200);
    }

    public function testLogin()
    {
        \Artisan::call('passport:install');
        $password = '1234567890';
        $user = factory(User::class)->create(['password' => bcrypt($password)]);

        $route = route('login');
        $payload = [
            'email' => $user->email,
            'password' => $password,
        ];

        $response = $this->post($route, $payload);

        $response
            ->assertStatus(200)
            ->assertJsonStructure([
                'data' => [
                    'token_type',
                    'token',
                    'expires_at',
                ],
            ]);

        $responseToken = $response->json()['data']['token'];
        $authedUser = Auth::user()->withAccessToken($responseToken);
        $this->assertEquals($user->id, $authedUser->id);
    }

    public function testLogout()
    {
        \Artisan::call('passport:install');
        $password = '1234567890';
        $user = factory(User::class)->create(['password' => bcrypt($password)]);

        $route = route('login');
        $payload = [
            'email' => $user->email,
            'password' => $password,
        ];

        $response = $this->post($route, $payload);

        $route = route('logout');
        $this->post($route /* LOGOUT */);
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question