Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created April 4, 2016 19:00
Show Gist options
  • Select an option

  • Save chrisguitarguy/9ae366c9bd48d26cd02be8ad5dd79d6f to your computer and use it in GitHub Desktop.

Select an option

Save chrisguitarguy/9ae366c9bd48d26cd02be8ad5dd79d6f to your computer and use it in GitHub Desktop.
Some interesting behavior with PHPUnit mocks & return types that are final classes.
<?php
// The return type of a method, imagine this is a
// nice value object.
final class Foo
{
}
// interface that returns a `Foo` value object
interface Bar
{
public function stuff() : Foo;
}
class Qux
{
private $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
public function doAThing()
{
$this->bar->stuff();
}
}
class Test extends \PHPUnit_Framework_TestCase
{
private $bar, $qux;
// this produces a warning, "Final Classes Can't be Mocked"
public function testCannotMockCallsToMethodsWithFinalReturnTypes()
{
$this->bar->expects($this->once())
->method('stuff');
$this->qux->doAThing();
}
// but this works just fine.
public function testMockingCallsAndSpecifyingAReturnManuallWorksJustFine()
{
$this->bar->expects($this->once())
->method('stuff')
->willReturn(new Foo());
$this->qux->doAThing();
}
protected function setUp()
{
$this->bar = $this->getMock(Bar::class);
$this->qux = new Qux($this->bar);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment