我使用 bake 生成用户表的控制器,现在我需要使用PHPUnit
和{{进行测试1}}如果已在数据库中输入记录但我无法确定是否实际插入了该记录。
我无法应用此解决方案:Question
第一个错误:
1)App \ Test \ TestCase \ Controller \ UsersControllerTest :: testAdd失败 声明''包含'用户已被保存。“。
如果我删除断言(或更改为assertResponseSuccess)
CakePHP 3
在assertEquals中,数组$this->assertResponseContains('The user has been saved.');
为空。
在UsersController中添加Action:
$result
在UsersControllerTest中的testAdd:
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$userTypes = $this->Users->UserTypes->find('list', ['limit' => 200]);
$this->set(compact('user', 'userTypes'));
$this->set('_serialize', ['user']);
}
数据源测试:
public function testAdd()
{
$this->get('/users/add');
$this->assertResponseOk();
//-------------------------------------------------------------------------
$data = [
'id' => 999999,
'email' => 'usuariocomum999999@gmail.com',
'password' => 'usuariocomum999999senha',
'username' => 'usuariocomum999999username',
'user_type_id' => 900000,
'created' => '2014-07-17 18:46:47',
'modified' => '2015-07-17 18:46:47'
];
$this->post('/users/add', $data);
$this->assertResponseContains('The user has been saved.');
//-------------------------------------------------------------------------
$expected = [
[
'id' => 999999,
'email' => 'usuariocomum999999@gmail.com',
'password' => 'usuariocomum999999senha',
'username' => 'usuariocomum999999username',
'user_type_id' => 900000,
'created' => new Time('2014-07-17 18:46:47'),
'modified' => new Time('2015-07-17 18:46:47')
]
];
$users = TableRegistry::get('Users');
$query = $users->find('all', [
'fields' => ['Users.id', 'Users.email', 'Users.password',
'Users.username', 'Users.user_type_id', 'Users.created',
'Users.modified'],
'conditions' => ['Users.id' => 999999]
]);
$result = $query->hydrate(false)->toArray();
$this->assertEquals($expected, $result);
}
注意: CakePHP 3.0.11和PHPUnit 4.8.6
答案 0 :(得分:1)
您需要测试Session
中是否存在重定向和成功消息,响应将不包含您的文本,因为响应只是浏览器的重定向标头代码。