【发布时间】:2018-06-05 15:17:20
【问题描述】:
CakePHP 版本:3.5.17
PHPUnit:6.5.8
示例代码:
用户控制器添加操作。 (错误的代码。)
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
// Initialise the client id.
if ($this->clientId() === false) {
//$errorLocation = 'Users Controller - Line ' . __LINE__;
//if ($this->recordError($errorLocation) === false) {
//throw new UnauthorizedException();
//}
//throw new UnauthorizedException();
}
else {
$clientID = $this->clientId();
}
$user = $this->Users->patchEntity($user, $this->request->getData());
// Declare the client id for save.
$user->cid_1 = $clientID;
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
客户端 ID 功能。
public function clientId()
{
$session = $this->request->session();
if ($session->check('Cid.one')) {
$clientID = $session->read('Cid.one');
if (!is_string($clientID) || is_numeric($clientID) || (strlen($clientID) !== 40)) {
return false;
}
return $clientID;
}
return false;
}
过程。
当用户登录时,我选择 $clientID 并将其存储在会话中,并在应用程序中的许多选择语句中使用它。
错误。
未定义的变量 clientID - EG:未从保存时出错的函数检索客户端 ID。
总结。
这对我来说很有意义,因为我可以在不登录的情况下运行单元测试,并且在登录时检索客户端 ID。 EG:测试的时候怎么会有client id!
我的解决方案。
我没有使用会话,而是使用如下所示的查找器。
用户控制器添加操作。 (通过的代码。)
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
// Declare the id from auth component.
$id = $this->Auth->user('id');
// Select the client id.
$query = $this->Users->find('cid', [
'id' => $id
]);
if ($query->isEmpty()) {
$errorLocation = 'Users Controller - Line ' . __LINE__;
if ($this->recordError($errorLocation) === false) {
throw new NotFoundException();
}
throw new NotFoundException();
}
// Initialise the variables and retrieve the data.
$clientID = '';
foreach ($query as $row):
$clientID = $row->cid_1;
endforeach;
$user = $this->Users->patchEntity($user, $this->request->getData());
// Declare the client id for save.
$user->cid_1 = $clientID;
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
我的问题:
有没有办法模拟会话中的 $clientID 以进行测试?
我想知道是否有类似使用的东西: $this->session(['Auth.User.id' => 1400]);在我模拟的测试中 经过身份验证的用户,但对于其他会话数据(例如客户端 ID)?
我为什么要问。
这与性能有关。据我所知,从会话中声明一个值比从数据库中选择一个值要快。
谢谢 Z。
【问题讨论】:
-
显示的代码中不能有“未定义变量”错误,逻辑要么抛出异常,要么定义变量。请确保您发布了正确的代码。
-
@ndm - 很抱歉,我在调试时注释掉了异常以显示未定义的变量错误,而在发布时忘记注释掉。我现在已经编辑了我的帖子,所以它应该可以正确阅读。
-
您是否尝试过使用
$this->session(['Cid.one' => XXX]);?看来你知道用$this->session写Auth数据;它也应该可以将您可能想要的任何其他内容写入会话中。 -
@Greg Schmidt - 我确实尝试过,但我仍然无法通过测试,但我刚刚再次尝试并且它有效,所以我不确定我上次做错了什么.此外,即使它起作用了,我仍然无法确定我是否正确使用了该框架,因此得到确认是一个很大的帮助。如果您将其发布为答案,我将勾选正确,非常感谢您的帮助。
标签: phpunit cakephp-3.0