beforeControllerAction
is parent method from any 'mycontroller' app controller, coming from framework core. You don't need to test specific core framework code (is already tested). You need to test your own code.
One way to test your controller is to extend/inherit your own 'mycontroller' controller first and build a test for it. Taken from this excellent article:
Create your unit test class under the protected/tests/unit
folder and name it the same as your class name you want to test,
adding a Test
word after it.
In my case, I will create a file named ApiControllerTest.php that
contains all tests for ApiController.php class.
<?php
// You can use Yii import or PHP require_once to refer your original file
Yii::import('application.controllers.ApiController');
class ApiControllerTest extends ApiController
{
}
Open your ApiControllerTest.php unit test class in step #1
above and make it something similar like this (based on your
requirement and structure):
class ApiControllerTest extends CTestCase
{
public function setUp()
{
$this->api = new ApiController(rand());
}
public function tearDown()
{
unset($this->api);
}
}
Let’s try to test one single method in my ApiController.php, that is
formatResponseHeader. This is what it is doing.
public function formatResponseHeader($code)
{
if (!array_key_exists($code, $this->response_code))
{
$code = '400';
}
return 'HTTP/1.1 ' . $code . ' ' . $this->response_code[$code];
}
Now, to test this method, I’ll open ApiControllerTest.php and add this
code below after setUp() and before tearDown() methods:
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'));
}
Save the change in ApiControllerTest.php and then try to run this in
protected/tests directory:
phpunit .
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…