gamez / psr-testlogger
PSR-3 compliant test logger for developers who like tests and want to check if their application logs messages as they expect.
Fund package maintenance!
jeromegamez
Installs: 185 767
Dependents: 13
Suggesters: 0
Security: 0
Stars: 8
Watchers: 1
Forks: 1
Open Issues: 0
Requires
- php: ^7.0
- psr/log: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.12
- phpunit/phpunit: ^6.0
Provides
- psr/log-implementation: ^1.0
README
PSR-3 compliant test logger for developers who like tests and want to check if their application logs messages as they expect.
This package was superseded by beste/psr-testlogger.
Installation
composer require --dev gamez/psr-testlogger
Usage
Inject an instance of Gamez\Psr\Log\TestLogger
into your Subject Under Test
instead of your regular logger.
use Psr\Log\LoggerInterface; class SubjectUnderTest { public function __construct(LoggerInterface $logger) { $this->logger = $logger; } public function execute() { $this->logger->info('Message with a {placeholder}', ['placeholder' => 'value']); $this->logger->emergency('This {placeholder} will not be replaced.'); } }
use Gamez\Psr\Log\TestLogger; use PHPUnit\Framework\TestCase; class MyTest extends TestCase { /** * @var TestLogger */ private $logger; /** * @var SubjectUnderTest */ private $sut; protected function setUp() { $this->logger = new TestLogger(); $this->sut = new SubjectUnderTest($this->logger); } public function testLogging() { $this->sut->execute(); $log = $this->logger->log; $this->assertTrue($log->has('Message with a value')); $this->assertTrue($log->hasRecordsWithContextKey('foo')); $this->assertFalse($log->hasRecordsWithContextKeyAndValue('foo', 'unwanted')); // This will break $this->assertFalse($log->hasRecordsWithUnreplacedPlaceholders()); } }
You can find all available helper methods in the Gamez\Psr\Log\Log
class. If it
doesn't provide a method you need, you can use your own filters:
use Gamez\Psr\Log\Record; use Gamez\Psr\Log\TestLogger; use PHPUnit\Framework\TestCase; class MyTest extends TestCase { /** * @var TestLogger */ private $logger; /** * @var SubjectUnderTest */ private $sut; protected function setUp() { $this->logger = new TestLogger(); $this->sut = new SubjectUnderTest($this->logger); } public function testSomethingSpecial() { $filteredLog = $this->logger->log->filter(function (Record $record) { // Matches messages with only numbers return ctype_digit($record->message); }); $this->assertCount(0, $filteredLog); } }