magmatic's avatar

In a test, how do I assert that nothing was logged?

For the life of me, I can't figure this out.

1 like
4 replies
vincent15000's avatar

You could for example check the content of the log file and assert that the file is empty.

JussiMannisto's avatar

You can use Monolog's test handler. The cleanest approach is to create a separate logging channel for tests:

// config/logging.php:
'channels' => [
	(...)
	
	'tests' => [
		'driver' => 'monolog',
		'handler' => Monolog\Handler\TestHandler::class,
	],
];
// phpunit.xml:
<env name="LOG_CHANNEL" value="tests"/>
// Test case:
/** @var Monolog\Handler\TestHandler $handler */
$handler = Log::getLogger()->getHandlers()[0];

logger('Debug message');
$this->assertTrue($handler->hasDebugRecords());

report('Error message');
$this->assertTrue($handler->hasErrorRecords());

$this->assertFalse($handler->hasInfoRecords());

2 likes
gfucci's avatar

You could get the log file, split and filter the content to transform it into a readable array, then take the last element and compare it with the value you expect in the log.

Use the File facade for this.

1 like

Please or to participate in this conversation.