|
4 | 4 | In all of the examples so far, the `thenReturn()` answer is being used. There are other answers that are remarkably
|
5 | 5 | useful writing your tests.
|
6 | 6 |
|
| 7 | +Returning the object itself |
| 8 | +--------------------------- |
| 9 | + |
| 10 | +When stubbing a method that can return the instance of the object itself (`$this`), it can be required to force the answer |
| 11 | +to be the instance of the mock. Rather than calling `thenReturn()` with the same mock variable as argument, Phake provides |
| 12 | +a cleaner way by calling the method `thenReturnSelf()`. |
| 13 | +Consider the following interface and class. |
| 14 | + |
| 15 | +```php-inline |
| 16 | +interface MyInterface |
| 17 | +{ |
| 18 | + public function foo(): ?static; |
| 19 | +
|
| 20 | + public function bar(): int; |
| 21 | +} |
| 22 | +``` |
| 23 | + |
| 24 | +```php-inline |
| 25 | +class MyClass |
| 26 | +{ |
| 27 | + public function useFooBar(MyInterface $object): ?int |
| 28 | + { |
| 29 | + return $object->foo()?->bar(); |
| 30 | + } |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | +As `MyInterface::foo()` is not always returning the instance of the object calling, a unit test trying to cover `MyClass` that |
| 35 | +uses any instance of such interface would require to stub `static` as answer. |
| 36 | + |
| 37 | +```php-inline |
| 38 | +class MyClassTest extends PHPUnit\Framework\TestCase |
| 39 | +{ |
| 40 | + public function testUseFooBar(): void |
| 41 | + { |
| 42 | + $mock = Phake::mock(MyInterface::class); |
| 43 | + Phake::when($mock)->foo()->thenReturnSelf(); |
| 44 | + Phake::when($mock)->bar()->thenReturn(42); |
| 45 | +
|
| 46 | + self::assertSame(42, (new MyClass())->useFooBar($mock)); |
| 47 | +
|
| 48 | + $mock = Phake::mock(MyInterface::class); |
| 49 | + Phake::when($mock)->foo()->thenReturn(null); |
| 50 | +
|
| 51 | + self::assertNull((new MyClass())->useFooBar($mock)); |
| 52 | + } |
| 53 | +} |
| 54 | +``` |
| 55 | + |
7 | 56 | Throwing Exceptions
|
8 | 57 | -------------------
|
9 | 58 |
|
|
0 commit comments