Can you use $ this inside a callback to get the protected properties of a mocked class in phpunit? Or is there another way to achieve this?
$mock = $this->getMock('A', array('foo')); $mock->expects($this->any())->method('foo')->will( $this->returnCallback(function() { return $this->bar; }));
This can be really useful if you are thinking about introducing mocking objects. Sometimes a class has a hard-coded dependency for another class, but it creates it using a method that you could theoretically scoff at creating and mocking an object instead of a hard-coded object. Take a look at another example.
class A { protected $bar = "bar"; public function foo () { $b = new B(); return $b->fizz($this->bar); } } class B { public function fizz ($buzz) { return $buzz; } }
But let's say class B does something bad, and I would like to replace it with a layout.
$mockB = $this->getMock('B'); // (...) - and probably mock other things $mockA = $this->getMock('A', array('foo')); $mockA->expects($this->any())->method('foo')->will( $this->returnCallback(function() use ($mockB) { return $mockB->fizz($this->bar); }));
As much as possible?
Of course, without any surprise, at present, if I do this as above, I get the error:
PHP Fatal error: Using $this when not in object context in (...)
Using the use keyword, I can inherit $ mockA from the parent scope:
$mockB = $this->getMock('B'); // (...) - and probably mock other things $mockA = $this->getMock('A', array('foo')); $mockA->expects($this->any())->method('foo')->will( $this->returnCallback(function() use ($mockA, $mockB) { return $mockB->fizz($mockA->bar); }));
but in this way I try to open the access panel as public, and I get:
PHP Fatal error: Cannot access protected property (...)