我有一个DoctorsController
,其store
方法。我正在测试这种方法,我希望我的模型不要在测试环境中INSERT
他们的数据。所以我在我的控制器和我的测试方法中使用DB::beginTransaction
,DB::rollback()
,DB::commit()
方法来阻止INSERT
查询。我的问题是=>我的测试正在运行时,数据库正在记录。我不希望在测试期间有任何INSERTS
。
我的测试代码:
public function testStoreMethod()
{
/*
* Test when validation fails
*/
$data = include_once('DoctorsControllerFormData.php');
foreach($data as $item){
DB::beginTransaction();
$response = $this->call('POST', 'doctors', $item);
$this->assertResponseStatus(400, "response's HTTP code is not 400 : " . implode('\n',array_flatten($item)));
Log::debug($response);
DB::rollback();
}
}
我的DoctorsController代码段(调用UsersController's
store
方法)
public function store()
{
//some code
DB::beginTransaction();
try{
/*
* User Creation
*/
$user = new UsersController();
$user->setResource('doctor');
$userID = $user->store();
//some other code
}catch (InputValidationFailedException $e){
DB::rollback();
return Response::make(json_encode(array('error' => $e->getErrors())), \Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
}catch(Exception $e){
Log::error('Server Error at DoctorsController');
DB::rollback();
App::abort(500, $e->getMessage());
}
}
我的UsersController代码段:
public function store()
{
$user = new User;
try{
$inputs = Input::all();
Log::info("input Data" . implode("\n", array_flatten(Input::all())));
/*
* User Creation
*/
$v = Validator::make(
$inputs,
User::$rules
);
if($v->fails()) {
Log::error('Validation Failed! ' . implode("\n", array_flatten($v->messages()->all())));
throw new InputValidationFailedException($v);
}
$user->fname = Input::get('fname');//set first name
$user->lname = Input::get('lname');//set last name
$user->email = Input::get('email');//set email
$user->cell = Input::get('cell');//set cell number
$user->password = Hash::make(Input::get('password'));//set password
$user->gender_id = Input::get('gender') == 'm' ? 1 : 0;//set gender
$user->is_active = 0;//set activation status
$user->role_id = ($this->resource == 'doctor') ? 1 : 2;
$user->activation_time = 0;//set activation time default to 0
$user->expiration_time = 0;//set expiration time default to 0
//insert the user into DB
$user->save();
}catch (InputValidationFailedException $e){
Log::info('User Validation Failed! ' . implode("\n", array_flatten($e->getErrors())));
throw $e;
}catch (Exception $e){
Log::error('Server Error at UsersController!');
throw $e;
}
return $user->id;
}
感谢您的帮助。
答案 0 :(得分:4)
如果您要提交控制器中的更改,则测试中的DB:rollback
无法撤消这些更改,因为事务已在那里完成。话虽这么说,你不应该像开发一样使用相同的数据库进行测试。 Laravel有Migrations & Seeding,您可以在任何时候运行测试时使用refresh and reseed专用测试数据库。
如果可能,我建议使用 in memory 数据库,以避免完全写入持久性数据库,如下面链接的视频中所述: