CakePHP版本:3.6.6
PHPUnit:6.5.8
//发生了什么
我的角色单元格测试应返回值时返回null。这导致我的测试失败,因为null与我的期望值不匹配。
//角色单元格
<?php
namespace App\View\Cell;
use Cake\View\Cell;
use Cake\ORM\TableRegistry;
/**
* Role cell
*/
class RoleCell extends Cell
{
/**
* List of valid options that can be passed into this cell's constructor.
*
* @var array
*/
protected $_validCellOptions = [];
/**
* Select the role for the page title on edit and view user.
*/
public function roleSingular($id = null)
{
// Ensure the id is an int when negotiating with the db.
if (!is_int($id)) {
$this->set('role', 'CELL_ERR');
}
else {
// Select the users role to display on the edit and view pages.
$Users = TableRegistry::getTableLocator()->get('Users');
$query = $Users->find('cellUsersRole', [
'id' => $id,
]);
// Check query not empty - Should have one result
if ($query->isEmpty()) {
$this->set('role', 'CELL_ERR');
}
else {
$role = '';
foreach ($query as $row):
$role = $row->role;
endforeach;
// Send the role to the edit and view for the page titles.
$this->set('role', $role);
// NOTE: Change above to return $role and the test works.
}
}
}
}
//角色单元测试
<?php
namespace App\Test\TestCase\View\Cell;
use App\View\Cell\RoleCell;
use Cake\TestSuite\TestCase;
/**
* App\View\Cell\RoleCell Test Case
*/
class RoleCellTest extends TestCase
{
/**
* Request mock
*
* @var \Cake\Http\ServerRequest|\PHPUnit_Framework_MockObject_MockObject
*/
public $request;
/**
* Response mock
*
* @var \Cake\Http\Response|\PHPUnit_Framework_MockObject_MockObject
*/
public $response;
/**
* Test subject
*
* @var \App\View\Cell\RoleCell
*/
public $RoleCell;
/**
* Fixtures.
*
* @var array
*/
public $fixtures = [
'app.users'
];
/**
* setUp method
*
* @return void
*/
public function setUp()
{
parent::setUp();
$this->request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
$this->response = $this->getMockBuilder('Cake\Http\Response')->getMock();
$this->RoleCell = new RoleCell($this->request, $this->response);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown()
{
unset($this->RoleCell);
parent::tearDown();
}
/**
* Test roleSingular method
*
* @return void
*/
public function testRoleSingular()
{
// Superuser.
$result = $this->RoleCell->roleSingular(1400);
$this->assertEquals('Superuser', $result);
}
}
//测试结果
无法断言null与预期的“超级用户”匹配。
//问题
为什么它返回null?
//调试
此测试与正常工作的组件测试非常相似。我唯一能确定的相关区别是,组件返回了值,而单元格则设置了值。
IE:
在组件中,我们使用:返回$ variable
在单元格中,我们使用: $ this-> set('role',$ role);
在此基础上,我将角色单元中的 $ this-> set('role',$ role); 更改为 return $ role ,并且测试成功了。 / p>
//参考
https://book.cakephp.org/3.0/en/views/cells.html#implementing-the-cell
//结论
据我所知,除非返回值,否则单元格测试将不起作用?到目前为止,《食谱》中尚未记录的单元格中,我们使用$ this-> set将值发送到视图。
希望有人可以帮助我了解发生了什么事?
谢谢Z。