8

I'm trying to mock a singleton using this method described by the author of PHPUnit and stub one of its methods:

public function setUp() {
    $this->_foo = $this->getMockBuilder('Foo')
        ->disableOriginalConstructor()
        ->getMock();

    $this->_foo->expects($this->any())
        ->method('bar')
        ->will($this->returnValue('bar'));

    var_dump($this->_foo->bar());
}

The problem is that this dumps NULL every time. As I understand it, when you mock an object, all the methods are replaced with stubs that return NULL unless explicitly stubbed like I'm doing. So, since I've stubbed the bar() method, why is it not dumping the expected 'bar' string? What have I done wrong?

3 Answers 3

3

I ran into the same problem, for me the issue turned out to be that the method I was invoking didn't exist on the original object, and was being handled by __call. The solution ended up looking like:

$this->_foo->expects($this->any())
    ->method('__call')
    ->with($this->equalTo('bar'))
    ->will($this->returnValue('bar'));
Sign up to request clarification or add additional context in comments.

Comments

1

I hope this can help, it's my entire replica of your problem. It prints out the desired 'bar'. I recommend checking that you are running the latest versions of phpunit and php i run:

PHPUnit 3.6.10 and PHP 5.4.6-1ubuntu1.

$suite  = new PHPUnit_Framework_TestSuite("TestTest");


class Foo {

    function Bar()
    {
        return null;
    }
}

class TestTest extends PHPUnit_Framework_TestCase 
{
    private $test_max_prod;
    private $initial;

    public function setUp() {
        $this->_foo = $this->getMockBuilder('Foo')
            ->disableOriginalConstructor()
            ->getMock();

        $this->_foo->expects($this->any())
            ->method('bar')
            ->will($this->returnValue('bar'));

        var_dump($this->_foo->bar());
    }

    function tearDown() {

    }

    function testTest(){}



}

Output

PHPUnit 3.6.10 by Sebastian Bergmann.

.string(3) "bar"


Time: 0 seconds, Memory: 2.50Mb

OK (1 test, 1 assertion)

I hope this was helpful.

Comments

1

This ended up being a problem with my PHPUnit version. I updated to the latest stable release, and was unable to duplicate the issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.