phpunit mock - method does not exist

蹲街弑〆低调 提交于 2019-12-22 04:38:07

问题


I recently updated PHPunit from 5.3 to 5.5 in an IntegrationTestCase of an app that is CakePhp 3.x based. and I don't understand how to update my mock generation scripts.

Originally I created my mock like this:

$stub = $this->getMock('SomeClass', array('execute'));
$stub->method('execute')
     ->will($this->returnValue($this->returnUrl));

After the change to PHPUnit 5.5 this got me the following warning:

PHPUnit_Framework_TestCase::getMock() is deprecated,
use PHPUnit_Framework_TestCase::createMock()
or PHPUnit_Framework_TestCase::getMockBuilder() instead

In order to fix this warning I changed the mock-generation to:

$stub = $this->getMockBuilder('SomeClass', array('execute'))->getMock();
$stub->method('execute')
     ->will($this->returnValue($this->returnUrl));```

Now I get the following error message when running the test:

exception 'PHPUnit_Framework_MockObject_RuntimeException' 
with message 'Trying to configure method "execute" which cannot be
configured because it does not exist, has not been specified, 
is final, or is static'

Anybody know, how to avoid this error? Thank you.


回答1:


PHPUnit_Framework_TestCase::getMockBuilder() only takes one (1) argument, the class name. The methods to mock are ment to be defined via the returned mock builder objects setMethods() method.

$stub = $this
    ->getMockBuilder('SomeClass')
    ->setMethods(['execute'])
    ->getMock();

See also

  • PHPUnit Manual > Test Doubles > Mock Objects



回答2:


I will leave this as an answer to myself, when i reach this problem again:

The mocked method may not be private.




回答3:


Addition to upper messages: split mock method declarations

Instead of this:

$mock
    ->method('persist')
       ->with($this->isInstanceOf(Bucket::class))
       ->willReturnSelf()
    ->method('save')
       ->willReturnSelf()
;

Use this:

$mock
    ->method('persist')
        ->willReturnSelf()
;

$mock
   ->method('save')
       ->willReturnSelf()
;



回答4:


First of all, it's just

$stub = $this->getMockBuilder('SomeClass')->getMock();

Second, error states that method execute does exist in your class SomeClass.

So, check if it really exists and it's public and not final.

If everything's good, check a full classname, if it real and specified with correct namespace.

To avoid stupid errors with classname, it's better to use this syntax:

$stub = $this->getMockBuilder(SomeClass::class)->getMock();

In this case, if SomeClass doesn't exist or namespace is missed, you will get a clear error about it.




回答5:


Perhaps , the method does not exist in the class that you mock .



来源:https://stackoverflow.com/questions/39601142/phpunit-mock-method-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!