How to avoid code duplication in the test phpunit?

Created test three methods to test the registration, login, logout (REST API, Laravel Passport), immediately struck by the fact that we have half the code from testLogin copy-paste in testLogout because otherwise the base at the time testLogout will not contain the user (transfer it via @depends does not make sense), there is an idea to put the code for the creation and login of a user in a private method and use it to testLogin and testLogout don't know as well.
Yes about the setUp, but it runs before each method, and before testRegister this code is not needed.

Example:
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 */);
}
}

April 7th 20 at 15:35
0 answer

Find more questions by tags PHPPHPUnit