0

I am learning unit testing with PHPUnit and am running into a strange problem with mock objects that I can't resolve. I set up these dummy files as an example of what I am experiencing:

Class1

class PrimaryObj1
{
    function doNothing(SecondObj $s)
    {
    }
}

Class2

class PrimaryObj2
{
    function doNothing(SecondObj $s)
    {
        $s->TestMethod();
    }
}

and a test file as:

class PrimaryObj1_test extends PHPUnit_Framework_TestCase
{
    private $primaryObj;
    function setUp()
    {
        $this->primaryObj = new PrimaryObj1();
    }
    function testDoNothing()
    {
        $secondObj = $this->getMock('SecondObj');
        $secondObj->expects($this->once())
                  ->method("TestMethod");
        $this->primaryObj->doNothing($secondObj);
    }
}

(one test file for each dummy class where everything is the same except for the class name).

When I run PHPUnit, this is what I get:

Running Tests/PrimaryObj1_test.php
1) PrimaryObj1_test::testDoNothing
Expectation failed for method name is equal to <string:TestMethod> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

Running Tests/PrimaryObj2_test.php
Fatal error: Call to undefined method Mock_SecondObj_99c898e7::TestMethod() in PrimaryObj2.php on line 5

So first it is mad that it didn't call the expected method but then when I do it gets mad cause it is undefined. I just can't win. I think this is why I'm still single...

Any thoughts on why this might be happening?

3
  • Show code of SecondObj Commented May 1, 2013 at 18:57
  • SecondObj only exists as a Mock. It has no code or class declaration Commented May 1, 2013 at 19:03
  • AFAIK the mocked class must exist Commented May 1, 2013 at 19:04

1 Answer 1

1

I got a response from an email list serve with the answer. This line:

    $secondObj = $this->getMock('SecondObj');

should be:

    $secondObj = $this->getMock('SecondObj', array('TestMethod'));

Once I made that change it worked as expected.

Sign up to request clarification or add additional context in comments.

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.