Created
September 28, 2023 22:06
-
-
Save vudaltsov/3d8baa7f8870bc429b12d2fa0bc098df to your computer and use it in GitHub Desktop.
LoggerStub
This file contains 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); | |
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]; | |
} | |
} |
This file contains 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); | |
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']); | |
// ... | |
} | |
} |
This file contains 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); | |
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