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并将其存储在会话中,然后在应用程序内的许多select语句中使用它。
The error。
未定义变量clientID - EG:未从保存时出错的函数中检索客户端id。
摘要。
这对我来说很有意义,因为我可以在没有登录的情况下运行单元测试,并且在登录时检索客户端id。例如:测试时客户端id怎么会在那里!
我的解决方案。
我没有使用会话,而是使用如下所示的finder。
用户控制器添加操作。(通过的代码。)
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.
https://stackoverflow.com/questions/50703568
复制相似问题