Created
April 4, 2016 19:00
-
-
Save chrisguitarguy/9ae366c9bd48d26cd02be8ad5dd79d6f to your computer and use it in GitHub Desktop.
Some interesting behavior with PHPUnit mocks & return types that are final classes.
This file contains hidden or 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 | |
| // 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