gamez/psr-testlogger

该软件包已被放弃,不再维护。作者建议使用beste/psr-testlogger软件包。

符合PSR-3规范的测试日志记录器,适用于喜欢测试并希望检查其应用程序是否按照预期记录消息的开发者。

3.0.0 2018-06-11 00:22 UTC

This package is auto-updated.

Last update: 2022-09-24 15:59:20 UTC


README

符合PSR-3规范的测试日志记录器,适用于喜欢测试并希望检查其应用程序是否按照预期记录消息的开发者。

此软件包已被beste/psr-testlogger取代。

Packagist Supported PHP version Build Status GitHub license Total Downloads

安装

composer require --dev gamez/psr-testlogger

使用方法

Gamez\Psr\Log\TestLogger实例注入到您的测试对象中,而不是使用常规的记录器。

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

您可以在Gamez\Psr\Log\Log中找到所有可用的辅助方法。如果没有提供您需要的函数,您可以使用自己的过滤器。

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