Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Mock Objects never expect by default

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?

like image 612
Bakyt Abdrasulov Avatar asked Nov 29 '12 11:11

Bakyt Abdrasulov


2 Answers

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.

like image 148
Cyprian Avatar answered Nov 13 '22 07:11

Cyprian


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'));
like image 25
Laurent Sarrazin Avatar answered Nov 13 '22 06:11

Laurent Sarrazin