【发布时间】:2017-08-06 13:37:25
【问题描述】:
我目前正在测试一个简单地按给定 id 搜索记录的应用程序。 它工作正常,但测试拒绝返回代码中的响应。奇怪的是它只显示在 CLI 中。
我使用的是 cakephp 提供的 phpunit:
"phpunit/phpunit": "^5.7|^6.0"
这里是冲突的代码:
$this->post('/comunas/findByBarrio',[
'barrio_id'=>1
]);
var_dump($this->_response->body());die(); //This is just a test which always returns NULL... while the CLI shows the actual response, which is a JSON.
在对任何其他操作执行 GET 或 POST 时也会出现同样的问题。 但这里是目标控制器的代码:
public function findByBarrio()
{
$this->autoRender = false;
if ($this->request->is('POST'))
{
$data = $this->request->getData();
if (!empty($data['barrio_id']))
{
$this->loadModel('Comuna');
$barrio_id = $data['barrio_id'];
$comuna = $this->Comuna->find('list',['conditions' => ['barrio_id'=>$barrio_id]])
->hydrate(false)
->toArray();
if ($comuna)
{
echo json_encode($comuna);
}
else
{
throw new NotFoundException('0');
//echo 0; //Comuna no encontrada para el barrio recibido
}
}
else
{
echo -1;
}
}
}
提前谢谢你!
更新 1:我只能通过在“$this->post”方法周围使用“ob_start()”和“ob_get_clean()”来获得输出。我希望有一种更清洁的方式......
更新 2:现在可以使用了!只需使用符合 PSR-7 的接口即可。谢谢! 这是更正后的控制器:
public function findByBarrio()
{
$this->autoRender = false;
$this->response = $this->response->withType('json'); //CORRECTION
if ($this->request->is('POST'))
{
$data = $this->request->getData();
if (!empty($data['barrio_id']))
{
$this->loadModel('Comuna');
$barrio_id = $data['barrio_id'];
$comuna = $this->Comuna->find('list',['conditions' => ['barrio_id'=>$barrio_id]])
->hydrate(false)
->toArray();
if ($comuna)
{
$json = json_encode($comuna);
$this->response->getBody()->write($json); //CORRECTION
}
else
{
//Comuna no encontrada para el barrio recibido
$this->response->getBody()->write(0); //CORRECTION
}
}
else
{
//No se recibió el barrio
$this->response->getBody()->write(-1); //CORRECTION
}
}
return $this->response; //CORRECTION
}
【问题讨论】:
-
控制器动作代码是什么样的?
-
任何动作都会发生这种情况,即使是最简单的动作。即便如此,我现在添加了该代码。谢谢
-
那么我假设你所有的控制器动作都编码不正确;)
标签: cakephp integration-testing cakephp-3.4