I have a large amount of tests in a TestCase. I want to set up a mock object that returns the same value in most of the tests, but in a few of the tests I would like to customize that value.
My idea was to create a set_up()
method (I was unable to set expectations inside the automatically invoked setUp()
), and to manually call it at the beginning of each test. In this method, I would set the default return value, then in the few tests that need to customize the return value, I would call expects a second time, and hopefully overwrite the default return value. This does not work, the return value is not overwritten.
Here is a simplified example:
<?php
class SomeClass {
function someMethod() {
}
}
class SomeTest extends PHPUnit_Framework_TestCase {
private $mock;
function set_up() {
$this->mock = $this->getMockBuilder('SomeClass')
->disableOriginalConstructor() // This is necessary in actual program
->getMock();
$this->mock->expects($this->any())
->method('someMethod')
->will($this->returnValue(1));
}
function test() {
$this->set_up();
$this->mock->expects($this->any())
->method('someMethod')
->will($this->returnValue(2));
$this->assertEquals(2, $this->mock->someMethod());
}
}
It seems that this should be possible from reading How to reset a Mock Object with PHPUnit.
PHPUnit mock with multiple expects() calls does not answer my question.
I am using phpUnit 4.2