Video in progress

Strong Middle 🧪 Testing

How do you test that code writes an important condition to the log (for example, a payment error or an audit entry), and when is that appropriate?

You can catch console output with Spring Boot's OutputCaptureExtension, or catch the log events that hit a specific logger with Logback's ListAppender, and check them. But if the log is a business requirement (audit), it's better to make it a separate dependency or a metric, because log text changes often.

📖 Answer

The most useful case is checking "what must not end up in the log". For example, on a payment error, the card number or token must not be written to the log:

@ExtendWith(OutputCaptureExtension.class)
class PaymentClientLoggingTest {

    @Test
    void failedChargeDoesNotLogCardNumber(CapturedOutput output) {
        assertThatThrownBy(() -> client.charge(card("8600123412341234"), 50_000))
            .isInstanceOf(PaymentDeclinedException.class);

        assertThat(output).contains("charge declined");
        assertThat(output).doesNotContain("8600123412341234");
    }
}

OutputCaptureExtension captures System.out/System.err, so the logger has to write to the console. If you need finer control (level, MDC, exception), connect to Logback directly:

var logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(PaymentClient.class);
var appender = new ListAppender<ILoggingEvent>();
appender.start();
logger.addAppender(appender);
try {
    // ... the call
    assertThat(appender.list).anySatisfy(e -> {
        assertThat(e.getLevel()).isEqualTo(Level.ERROR);
        assertThat(e.getMDCPropertyMap()).containsKey("orderId");
    });
} finally {
    logger.detachAppender(appender);
}

You must remove the appender in finally, otherwise it keeps collecting during later tests; and in parallel tests, sharing one logger mixes up the results.

When a log test is the wrong choice: if an audit entry like "the user cancelled" is needed for reports and checks, it's data, not a log. Make it an AuditLog interface or a MeterRegistry counter, and check it in the test with a SimpleMeterRegistry or a fake. Tests that rely on log text break on every wording change.