Testing

Testing your logging code with WPZylos Logger.

Unit Testing

Mock Logger

use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;

class PaymentServiceTest extends TestCase
{
    public function testPaymentLogsSuccess(): void
    {
        $logger = $this->createMock(LoggerInterface::class);

        $logger->expects($this->exactly(2))
            ->method('info')
            ->withConsecutive(
                ['Processing payment', $this->anything()],
                ['Payment successful', $this->anything()]
            );

        $service = new PaymentService($logger);
        $service->processPayment($order);
    }

    public function testPaymentLogsFailure(): void
    {
        $logger = $this->createMock(LoggerInterface::class);

        $logger->expects($this->once())
            ->method('error')
            ->with('Payment failed', $this->anything());

        $service = new PaymentService($logger);

        $this->expectException(PaymentFailedException::class);
        $service->processPayment($invalidOrder);
    }
}

Test Logger

class TestLogger implements LoggerInterface
{
    public array $logs = [];

    public function log($level, $message, array $context = []): void
    {
        $this->logs[] = [
            'level' => $level,
            'message' => $message,
            'context' => $context,
        ];
    }

    // Implement other PSR-3 methods...

    public function assertLogged(string $level, string $message): void
    {
        foreach ($this->logs as $log) {
            if ($log['level'] === $level && str_contains($log['message'], $message)) {
                return;
            }
        }
        throw new \AssertionError("Expected log not found: [{$level}] {$message}");
    }

    public function assertNotLogged(string $level): void
    {
        foreach ($this->logs as $log) {
            if ($log['level'] === $level) {
                throw new \AssertionError("Unexpected log at level: {$level}");
            }
        }
    }
}

Using Test Logger

class UserServiceTest extends TestCase
{
    public function testCreateUserLogsInfo(): void
    {
        $logger = new TestLogger();
        $service = new UserService($logger);

        $service->create(['email' => '[email protected]']);

        $logger->assertLogged('info', 'User created');
    }
}

Running Tests

composer run test