4
votes

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

1

1 Answers

5
votes

You can pass arguments to set_up method so it can configure the mock as needed:

function set_up($someMethodReturnValue = 1) {
    $mock = $this->getMockBuilder('SomeClass')
        ->disableOriginalConstructor() // This is necessary in actual program
        ->getMock();
    $mock->expects($this->any())
        ->method('someMethod')
        ->will($this->returnValue($someMethodReturnValue));
    return $mock;
}


function test() {
    $mock = $this->set_up(2);
    $this->assertEquals(2, $this->mock->someMethod());
}

You can further enhance the set_up() method. Eventually you could create a Mock creation class if there are lots of options.