Skip to content

Instantly share code, notes, and snippets.

@Chemaclass
Created June 8, 2020 03:41
Show Gist options
  • Select an option

  • Save Chemaclass/d42d770150a717266aae972039511acb to your computer and use it in GitHub Desktop.

Select an option

Save Chemaclass/d42d770150a717266aae972039511acb to your computer and use it in GitHub Desktop.
An example using a Test Double Spy
<?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