I'm trying to work with Laravel 5.4 + PHPUnit for testing my classes. I created following class to test user controller:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
class UserControllerTest extends TestCase
{
protected $baseUrl = 'http://localhost/pmv2';
use DatabaseMigrations;
public function testCreatesUser()
{
echo "\nTest: POST /users => Create new user";
$data = [
'first_name' => 'first_new_user',
'last_name' => 'last_new_user',
'email' => '[email protected]',
'password' => 'new_password',
'phone_number' => '3333333333',
'status' => 'active',
'created_at' => '2000-1-1 10:10:00',
'updated_at' => '2000-1-1 10:10:00',
];
$response = $this->post('/users', $data);
$response->assertStatus(200);
$this->assertDatabaseHas('users', ['email' => $data['email']]);
}
public function testReadAllUsers()
{
$this->seed('UsersTableSeeder');
echo "\nTest: GET /users => Read all users";
$this->seed('UsersTableSeeder');
$response = $this->get('/users');
$response->assertStatus(200);
$response->assertJson([
'found' => true,
'users' => [],
]);
}
public function testReadSingleUser()
{
$this->seed('UsersTableSeeder');
echo "\nTest: POST /users => Read single user";
$response = $this->get('/users/1');
$response->assertStatus(200);
$response->assertJson([
'found' => true,
'user' => [],
]);
}
public function testUpdateUser()
{
$this->seed('UsersTableSeeder');
echo "\nTest: POST /users => Create new user";
$data = [
'first_name' => 'first_updated_user',
'last_name' => 'last_updated_user',
'email' => '[email protected]',
'password' => 'updated_password',
'phone_number' => '44444444444',
'updated_at' => '2000-1-1 10:10:00',
];
$response = $this->put('/users/1', $data);
$response->assertStatus(200);
$this->assertDatabaseHas('users', ['email' => $data['email']]);
}
}
The problem here is that database is refreshed for every single test. I need to refresh the migration only once before the very first test runs and after the last test.