PHPUnit Mock Objects never expect by default

ⅰ亾dé卋堺 提交于 2020-08-27 05:54:11

问题


Is there a way to tell a phpunit mock object to never expect the method calls if there are no formally defined expectations for them?


回答1:


In my opinion it's not got idea to never expectation for every method. So phpunit doesn't have any functionality. Can should use "never" expectations only if you want totally ensure that some method won't be called.

Anyway you can use some matchers to get closer your goal. Examples:

Never expectations for all object's methods (fails if any of mocked methods will be called):

$mock->expects($this->never())
    ->method($this->anything());

So, for example you can test that some object won't call any method apart from tested one:

$mock = $this->getMock('Some\Tested\Class', array('testedMethod'));
$mock->expects($this->never())
    ->method($this->anything());

You can try also with another matcher, eg. matchesRegularExpression:

$mock->expects($this->never())
    ->method($this->matchesRegularExpression('/get.*/'));

For example above will fail if any getter will be called.

I'm aware this is not exactly what You want, but I'm afraid there is no such solution with phpunit.




回答2:


If you want to test that a method is never called when a specific argument is given use

$mock->expects($this->any())
->method('foo')
->with(new PHPUnit_Framework_Constraint_Not('bar'));


来源:https://stackoverflow.com/questions/13624938/phpunit-mock-objects-never-expect-by-default

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