Skip to content

Commit b8459b0

Browse files
authored
Merge pull request #1 from niconoe-/patch-1
Add documentation about `thenReturnSelf()`
2 parents 202254c + f86b74a commit b8459b0

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/doc/answers.md

+49
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,55 @@ Answers
44
In all of the examples so far, the `thenReturn()` answer is being used. There are other answers that are remarkably
55
useful writing your tests.
66

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+
756
Throwing Exceptions
857
-------------------
958

0 commit comments

Comments
 (0)