Skip to content

Instantly share code, notes, and snippets.

@dj1020
Forked from pjdietz/cloudSettings
Created February 9, 2017 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj1020/a0816b5558a6eaf92e3930c70d29d677 to your computer and use it in GitHub Desktop.
Save dj1020/a0816b5558a6eaf92e3930c70d29d677 to your computer and use it in GitHub Desktop.
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