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.

3.0.0 2018-06-11 00:22 UTC

README

PSR-3 compliant test logger for developers who like tests and want to check if their application logs messages as they expect.

Packagist Supported PHP version Build Status GitHub license Total Downloads

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);
    }
}