Skip to content

Instantly share code, notes, and snippets.

@srdjanmarjanovic
Forked from pjdietz/cloudSettings
Created May 24, 2018 07:25
Show Gist options
  • Save srdjanmarjanovic/ae93464f61b427125f8d18da6d85b3fb to your computer and use it in GitHub Desktop.
Save srdjanmarjanovic/ae93464f61b427125f8d18da6d85b3fb 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