Testing Protected Method of Abstract Class with PHPUnit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Minitest; | |
abstract class AbstractFoo | |
{ | |
protected function bar() | |
{ | |
return $this->baz(); | |
} | |
abstract protected function baz(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class FooTest extends PHPUnit_Framework_TestCase | |
{ | |
public function testCallProtectedMethodOfAbstractClass() | |
{ | |
// Create a mock for the abstract class. | |
$foo = $this->getMockForAbstractClass('Minitest\AbstractFoo'); | |
// Provide the behavior for abstract methods. | |
$foo->expects($this->any()) | |
->method("baz") | |
->will($this->returnValue("You called baz!")); | |
// Define a closure that will call the protected method using "this". | |
$barCaller = function () { | |
return $this->bar(); | |
}; | |
// Bind the closure to $foo's scope. | |
$bound = $barCaller->bindTo($foo, $foo); | |
// $bound is now a Closure, and calling it is like asking $foo to call | |
// $this->bar(); and return the results. | |
// Make a assertion. | |
$this->assertEquals("You called baz!", $bound()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment