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?
-
What do you mean by "never expect"? As I've understood you mean the test should fail always if the mock object call method which wasn't explicity expected? Is that correct? – Cyprian Nov 29 '12 at 17:00
-
Yes, that is correct. I don't want to write `$mock->expects($this->never())->method('abc')` for each method that should not be called. – Bakyt Abdrasulov Nov 30 '12 at 04:27
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.

- 11,174
- 1
- 48
- 45
-
1That's awesome, I didn't know you could specify a regex for the method name. This way I can say ```expected($this->never())->method('|^goodMethod|')``` meaning that it should expect no calls to any method, except for the one called ```goodMethod()```. Not quite what the OP was asking for, but solved my problem. – rodrigo-silveira Jan 31 '15 at 11:33
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'));

- 774
- 4
- 9