I am probably missing something really trivial here, but I cannot get phpunit to use stand-in Mocked classes.
Below is an example where Foo is the class that I am testing and Bar the class that I want to Mock out.
I would expect below example to pass, since I have mocked Bar, stubbed out Bar::heavy_lifting to return “not bar” and then call that trough Foo::do_stuff().
Yet it fails, the example still returns “bar”, seems to completely ignore my stubbing.
class Foo {
public function do_stuff() {
$b = new Bar();
return $b->heavy_lifting();
}
}
class Bar {
public function heavy_lifting() {
return "bar";
}
}
class FooTest extends PHPUnit_Framework_TestCase {
public function testBar() {
$fake = "not bar";
$stand_in = $this->getMock("Bar");
$stand_in->expects($this->any())
->method("heavy_lifting")
->will($this->returnValue($fake));
$foo = new Foo();
$this->assertEquals($foo->do_stuff(), $fake);
}
}
Your code won’t work as expected. Stub is not about replacing Bar class, but to create objects that can be passed to where Bar is expected. You should refactor your Foo class like:
Than you can pass mocked Bar to class Foo.