Reputation: 655
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?
Upvotes: 0
Views: 3765
Reputation: 655
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.
Upvotes: 1