问题
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