Skip to content

Instantly share code, notes, and snippets.

@dj1020
Forked from pjdietz/cloudSettings
Created February 9, 2017 07:08
Testing Protected Method of Abstract Class with PHPUnit
<?php
namespace Minitest;
abstract class AbstractFoo
{
protected function bar()
{
return $this->baz();
}
abstract protected function baz();
}
<?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