关于zend框架:使用PHPUnit测试ZF控制器的受保护方法

Test protected methods of ZF controllers with PHPUnit

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

1
2
3
4
class AuthenticateController extends Zend_Controller_Action
{
    protected function getAuthAdapter(){}
}

我的测试(在这篇文章之后)看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
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);
}

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

1
2
3
4
5
6
7
8
9
10
11
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
2
3
4
$class = new AuthenticateController(
        new Zend_Controller_Request_HttpTestCase(),
        new Zend_Controller_Response_HttpTestCase()
    );