beforeControllerAction 是来自任何“mycontroller”应用控制器的父方法,来自框架核心。您不需要测试特定的核心框架代码(已测试)。您需要测试自己的代码。
测试您的控制器的一种方法是首先扩展/继承您自己的“mycontroller”控制器并为其构建测试。取自excellent article:
在 protected/tests/unit 下创建你的单元测试类
文件夹并将其命名为与您要测试的类名相同,
在其后添加一个Test 字。
在我的例子中,我将创建一个名为 ApiControllerTest.php 的文件
包含 ApiController.php 类的所有测试。
<?php
// You can use Yii import or PHP require_once to refer your original file
Yii::import('application.controllers.ApiController');
class ApiControllerTest extends ApiController
{
}
在第 1 步中打开您的 ApiControllerTest.php 单元测试类
上面并使其类似于这样(基于您的
要求和结构):
class ApiControllerTest extends CTestCase
{
public function setUp()
{
$this->api = new ApiController(rand());
}
public function tearDown()
{
unset($this->api);
}
}
让我们尝试在我的 ApiController.php 中测试一个方法,即
格式响应头。这就是它正在做的事情。
public function formatResponseHeader($code)
{
if (!array_key_exists($code, $this->response_code))
{
$code = '400';
}
return 'HTTP/1.1 ' . $code . ' ' . $this->response_code[$code];
}
现在,为了测试这个方法,我将打开 ApiControllerTest.php 并添加这个
下面的代码在 setUp() 之后和 tearDown() 方法之前:
public function testFormatResponseHeader()
{
$this->assertEquals('HTTP/1.1 400 Bad Request',$this->api->formatResponseHeader('400'));
$this->assertEquals('HTTP/1.1 200 OK',$this->api->formatResponseHeader('200'));
$this->assertEquals('HTTP/1.1 400 Bad Request',$this->api->formatResponseHeader('500'));
$this->assertNotEquals('HTTP/1.1 304 Not Modified',$this->api->formatResponseHeader('204'));
}
在 ApiControllerTest.php 中保存更改,然后尝试在其中运行它
protected/tests 目录:
phpunit .