Created
July 20, 2017 15:05
-
-
Save DragonBe/24761f350984c35b73966809dd439135 to your computer and use it in GitHub Desktop.
Testing final classes is tricky, but possible even though you cannot directly mock a "final" class
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 FinalClass; | |
require_once __DIR__ . '/vendor/autoload.php'; | |
use PHPUnit\Framework\TestCase; | |
final class Foo | |
{ | |
protected $bar; | |
public function __construct(BarInterface $bar) | |
{ | |
$this->bar = $bar; | |
} | |
public function bar() | |
{ | |
return 'Hello ' . $this->bar->getMessage() . '!'; | |
} | |
} | |
interface BarInterface {} | |
final class Bar implements BarInterface | |
{ | |
protected $message; | |
public function __construct() | |
{ | |
$this->message = 'World'; | |
} | |
public function getMessage() | |
{ | |
return $this->message; | |
} | |
} | |
class BarMock implements BarInterface | |
{ | |
protected $bar; | |
public function __construct() | |
{ | |
$this->bar = new \ReflectionClass(Bar::class); | |
} | |
public function __call($name, $args) | |
{ | |
$bar = $this->bar->newInstance($args); | |
return $bar->$name(); | |
} | |
} | |
class FooTest extends TestCase | |
{ | |
public function testFooReturnsMessage() | |
{ | |
$bar = $this->getMockBuilder(BarMock::class) | |
->setMethods(['getMessage']) | |
->getMock(); | |
$bar->expects($this->once()) | |
->method('getMessage') | |
->willReturn('World'); | |
$foo = new Foo($bar); | |
$this->assertSame('Hello World!', $foo->bar()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solves the issue Class "FinalClass\Bar" is declared "final" and cannot be mocked.
Error reporting by PHPUnit: