olvlvl
olvlvl

Reputation: 2454

Why is this mock failing? (from PHPUnit doc)

I created the following test, using PHPUnit documentation, and it fails with the following message:

PHP Fatal error:  Call to undefined method Mock_SomeClass_97937e7a::doSomething().

What's wrong? This is the example from the documentation. I'm using PHPUnit 4.4.0.

<?php

class SomeClass
{

}

class SomeClassTest extends PHPUnit_Framework_TestCase
{
    public function testStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMockBuilder('SomeClass')
            ->getMock();

        // Configure the stub.
        $stub->method('doSomething')
            ->willReturn('foo');

        // Calling $stub->doSomething() will now return
        // 'foo'.
        $this->assertEquals('foo', $stub->doSomething());
    }
}

Upvotes: 1

Views: 2717

Answers (2)

Kent Aguilar
Kent Aguilar

Reputation: 5338

Here's the snapshot:

  • Declare the "doSomething" method on your "SomeClass" class.
  • Use the "setMethods" routine after "getMockBuilder"
  • Instead of willReturn, use "will($this->returnValue('foo'))".

Here's my code:

class SomeClass
{
    public function doSomething()
    {

    }
}

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMockBuilder('SomeClass')
                        ->setMethods(array('doSomething'))
                        ->getMock();

        // Configure the stub.
        $stub->expects($this->any())
                ->method('doSomething')
                ->will($this->returnValue('foo'));

        // Calling $stub->doSomething() will now return
        // 'foo'.
        $this->assertEquals('foo', $stub->doSomething());
    }
}

Upvotes: 1

bbankowski
bbankowski

Reputation: 353

doSomething method is missing in SomeClass. You cannot mock a method that does not exist.

Upvotes: 1

Related Questions