Created
June 8, 2020 03:41
-
-
Save Chemaclass/d42d770150a717266aae972039511acb to your computer and use it in GitHub Desktop.
An example using a Test Double Spy
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 declare(strict_types=1); | |
| use PHPUnit\Framework\TestCase; | |
| interface Logger { | |
| public function log(string $message): void; | |
| } | |
| final class LoggerSpy implements Logger { | |
| public array $messages = []; | |
| public function log(string $message): void | |
| { | |
| $this->messages[] = $message; | |
| } | |
| } | |
| final class UserNotifier { | |
| private Logger $logger; | |
| public function __construct(Logger $logger) | |
| { | |
| $this->logger = $logger; | |
| } | |
| public function registerUser(User $user): void | |
| { | |
| $this->logger->log("Notifying the user {$user->name()}"); | |
| // Doing other stuff... | |
| } | |
| } | |
| final class UserNotifierTest extends TestCase { | |
| public function testLogMessages(): void | |
| { | |
| $logger = new LoggerSpy(); | |
| $notifier = new UserNotifier($logger); | |
| $notifier->registerUser(new User()); | |
| $this->assertStringContainsString('Notifying the user', end($logger->messages)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment