【发布时间】:2017-05-26 16:56:55
【问题描述】:
我正在尝试使用 Laravel 5.4 + PHPUnit 来测试我的课程。我创建了以下类来测试用户控制器:
<?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_new@pm.com',
'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_updated@pm.com',
'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']]);
}
}
这里的问题是每次测试都会刷新数据库。在第一次测试运行之前和最后一次测试之后,我只需要刷新一次迁移。
【问题讨论】:
标签: phpunit laravel-5.4