使用PHPUnit测试ZF控制器的受保护方法

时间:2011-06-07 10:10:39

标签: zend-framework reflection phpunit controllers

我想测试一个位于控制器内的受保护方法:

class AuthenticateController extends Zend_Controller_Action
{
    protected function getAuthAdapter(){}
}

我的测试(this帖后)看起来像这样:

public function testGetAuthAdapterShouldReturnZendAuthAdapterDbTable()
{
    require_once(APPLICATION_PATH.'/controllers/AuthenticateController.php');
    $method = new Zend_Reflection_Method('AuthenticateController', 
                                         'getAuthAdapter');
    $class = new AuthenticateController();
    $result = $method->invoke($class);

    // assert result value
    $this->assertInstanceOf('Zend_Auth_Adapter_DbTable', $result);
}

当我执行测试时,我得到了这个运行时异常

RuntimeException: Fatal error: Call to a member function getModuleName() on a non-object in /Users/padawan_rodrigo/Documents/workspace/ZendFramework-1.11.5/library/Zend/Controller/Action/Helper/ViewRenderer.php on line 226
Call Stack:
0.0030     396924   1. {main}() -:0
0.0755    4593044   2. __phpunit_run_isolated_test() -:207
0.0771    4718524   3. PHPUnit_Framework_TestCase->run() -:22
0.0785    4798460   4. PHPUnit_Framework_TestResult->run() /usr/local/pear/share/pear/PHPUnit/Framework/TestCase.php:576
0.3565    4827948   5. PHPUnit_Framework_TestCase->runBare() /usr/local/pear/share/pear/PHPUnit/Framework/TestResult.php:666
0.6696   10508956   6. PHPUnit_Framework_TestCase->runTest() /usr/local/pear/share/pear/PHPUnit/Framework/TestCase.php:628
0.6697   10509780   7. ReflectionMethod->invokeArgs() /usr/local/pear/share/pear/PHPUnit/Framework/TestCase.php:738
0.6697   10509796   8. AuthenticateControllerTest->testGetAuthAdapterShouldReturnZendAuthAdapterDbTable() /project/code/tests/application/controllers/AuthenticateControllerTest.php:0
0.6794   10753940   9. Zend_Controller_Action->__construct() /project/code/tests/application/controllers/AuthenticateControllerTest.php:172

我也尝试用相同的结果模拟这个类。有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

您需要将请求和响应传递给控制器​​的构造函数。

$class = new AuthenticateController(
        new Zend_Controller_Request_HttpTestCase(), 
        new Zend_Controller_Response_HttpTestCase()
    );