Undefined method on mock object implementing a given interface in PHPUnit?

前端 未结 3 2121
夕颜
夕颜 2021-02-07 04:34

I\'m new to unit testing and PHPUnit.

I need a mock, on which I have a full control, implementing ConfigurationInterface interface. Test subject is Re

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-07 05:26

    Cyprian's answer helped me, but there's a gotcha to be aware of. You can mock classes that don't exist, and PHPUnit won't complain. So you could do

    $mock = $this->getMock('SomeClassThatDoesntExistOrIsMisspelledOrPerhapsYouForgotToRequire');
    

    This means that if ConfigurationInterface doesn't exist at that point during runtime, you'll still get a message like

    Fatal error: Call to undefined method Mock_ConfigurationInterface_21e9dccf::getClass().

    If you're sure the method really exists on the class, then the likely problem is the class itself doesn't exist (because you haven't required it, or you misspelled it, etc).


    The OP is using an interface. Be advised that you must call getMock without specifying the list of methods to override, or if you do, you must either pass array(), or pass ALL the method names, or you'll get an error like the following:

    PHP Fatal error: Class Mock_HttpRequest_a7aa9ffd contains 4 abstract methods and must therefore be declared abstract or implement the remaining methods (HttpRequest::setOption, HttpRequest::execute, HttpRequest::getInfo, ...)

提交回复
热议问题