Skip to content

Instantly share code, notes, and snippets.

@vudaltsov
Created September 28, 2023 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vudaltsov/3d8baa7f8870bc429b12d2fa0bc098df to your computer and use it in GitHub Desktop.
Save vudaltsov/3d8baa7f8870bc429b12d2fa0bc098df to your computer and use it in GitHub Desktop.
LoggerStub
<?php
declare(strict_types=1);
namespace App;
use Psr\Log\AbstractLogger;
final class LoggerStub extends AbstractLogger
{
/**
* @var list<array{mixed, \Stringable|string, array}>
*/
public array $logs = [];
public function log($level, \Stringable|string $message, array $context = []): void
{
$this->logs[] = [$level, $message, $context];
}
}
<?php
declare(strict_types=1);
namespace App;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
final readonly class SomeService
{
public function __construct(
private LoggerInterface $logger = new NullLogger(),
) {}
public function doStuff(): void
{
// ...
$this->logger->info('I did it!', ['key' => 'value']);
// ...
}
}
<?php
declare(strict_types=1);
namespace App;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;
#[CoversClass(SomeService::class)]
final class SomeServiceTest extends TestCase
{
public function testItLogs(): void
{
$logger = new LoggerStub();
$service = new SomeService($logger);
$service->doStuff();
self::assertSame(
[[LogLevel::INFO, 'I did it!', ['key' => 'value']]],
$logger->logs,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment