PHPUnit测试double抛出PHPUnit_Framework_MockObject_BadMethodCallException

时间:2015-02-11 12:35:08

标签: php zend-framework phpunit

我试图创建一个模拟对象,并在测试时在我的Zend框架应用程序中使用它:

public function testAskQuestionRouteWithLoggedIn()
{
    // get the mock auth object, and update the registry
    $auth = $this->getMockBuilder('QA_Auth')
        ->disableOriginalConstructor()
        ->getMock();

    // mock methods, and return values
    $auth->method('isAuthenticated')
        ->will( $this->returnValue( true ) );

    // update the registry
    $auth = Zend_Registry::set('Auth', $auth);

    // now preform the test as a logged in user
    $this->dispatch('/ask');
    $this->assertController('questions');
    $this->assertAction('new');

    // // // check the page contains a question form
    $this->assertQueryCount('form#questionForm', 1);
}

...但是它抛出了一个PHPUnit_Framework_MockObject_BadMethodCallException异常,但实际上并没有多少(例如原因)。如果我在我的应用程序中执行echo get_class($auth); exit;,我可以看到它是Mock_QA_Auth_f4627b7b类,所以至少它已经获取了模拟实例。但是当我调用isAuthenticated方法时,它会抛出异常。我做错了什么?

以下是我看到的错误消息:

$ ./vendor/bin/phpunit tests/application/controllers/QuestionsControllerTest.php 
PHPUnit 4.4.2 by Sebastian Bergmann.

Configuration read from /var/www/vhosts/qasystem/qasystem/tests/application/phpunit.xml

E

Time: 277 ms, Memory: 7.50Mb

There was 1 error:

1) QuestonsControllerTest::testAskQuestionRouteWithLoggedIn
PHPUnit_Framework_MockObject_BadMethodCallException: 

/var/www/vhosts/qasystem/qasystem/application/controllers/BaseController.php:331
/var/www/vhosts/qasystem/qasystem/application/controllers/BaseController.php:29
/var/www/vhosts/qasystem/qasystem/application/controllers/QuestionsController.php:14
/var/www/vhosts/qasystem/qasystem/vendor/zendframework/zendframework1/library/Zend/Controller/Action.php:133
/var/www/vhosts/qasystem/qasystem/vendor/zendframework/zendframework1/library/Zend/Controller/Dispatcher/Standard.php:281
/var/www/vhosts/qasystem/qasystem/vendor/zendframework/zendframework1/library/Zend/Controller/Front.php:954
/var/www/vhosts/qasystem/qasystem/vendor/zendframework/zendframework1/library/Zend/Application/Bootstrap/Bootstrap.php:105
/var/www/vhosts/qasystem/qasystem/vendor/zendframework/zendframework1/library/Zend/Application.php:382
/var/www/vhosts/qasystem/qasystem/tests/application/controllers/BaseControllerTestCase.php:67
/var/www/vhosts/qasystem/qasystem/tests/application/controllers/QuestionsControllerTest.php:26

1 个答案:

答案 0 :(得分:5)

QA_Auth::isAuthenticated()是一种静态方法,静态方法无法模拟。

  

限制:最终,私有和静态方法

     

请注意,无法对最终,私有和静态方法进行存根或模拟。它们被PHPUnit的测试双重功能忽略,并保留其原始行为。

     

- Test Doubles

本手册说,测试会使双倍"保留其原始行为",但静态方法并非如此。有一个open issue about it。另请参阅PHPUnit Mock Objects and Static Methods