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?
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'));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With