Skip to content
javahacks.dev
JUnit

How to Test Exceptions Logs and Console Output in JUnit

Test exceptions, log output and System.out in JUnit 5: assertThrows, checking messages and causes, capturing logs with Logback appenders and console output.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the JUnit5, Selenium, Jenkins and GitHub Actions logos.

Some behaviour shows itself only through an exception, a log line or console output. A service that rejects a negative amount throws; an audit component writes a warning when a login fails; a command-line tool prints a greeting. JUnit handles exceptions directly and can be extended to capture the others. This guide covers testing exceptions, log events with Logback, Spring Boot's output capture, System.out redirection with its traps, the cleanup rules that keep tests independent and the design changes that make such tests unnecessary. Examples use JUnit 5.13 and Logback and apply to JUnit 6.

Exceptions

java
@Test
void rejectsNegativeAmount() {
    IllegalArgumentException ex = assertThrows(
        IllegalArgumentException.class,
        () -> Money.of(-1, "EUR"));

    assertEquals("amount must not be negative", ex.getMessage());
}

assertThrows fails if nothing is thrown or if the type differs, and it returns the exception so you can inspect it. Subclasses pass. For an exact type use assertThrowsExactly. With several checks together:

java
Throwable thrown = assertThrows(ServiceException.class, () -> service.load("x"));
assertAll(
    () -> assertTrue(thrown.getMessage().contains("x")),
    () -> assertInstanceOf(IOException.class, thrown.getCause())
);

Fluent versions exist in AssertJ, see AssertJ assertions, and the grouping is covered in assertThrows and assertAll. Assert on a message only when the message is part of the contract. Exact text invites breakage on every wording change, so prefer asserting on the type and on a stable fragment such as an identifier.

Logs with Logback

java
class AuditServiceTest {

    private final ListAppender<ILoggingEvent> appender = new ListAppender<>();
    private final Logger logger = (Logger) LoggerFactory.getLogger(AuditService.class);

    @BeforeEach
    void attach() {
        appender.start();
        logger.addAppender(appender);
    }

    @AfterEach
    void detach() {
        logger.detachAppender(appender);
    }

    @Test
    void logsWarningOnFailedLogin() {
        new AuditService().loginFailed("amy");

        assertThat(appender.list)
            .extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage)
            .contains(tuple(Level.WARN, "login failed for amy"));
    }
}

The ListAppender stores log events in a list. Attach it before the code runs and detach it afterwards. Assert on level and message, never on timestamps or thread names, which change every run. The cast to the Logback Logger ties the test to Logback, which is acceptable in a test, and the same idea works with Log4j's test appender. Spring Boot users can use OutputCaptureExtension, which captures console output without touching the logging system:

java
@ExtendWith(OutputCaptureExtension.class)
class LoggingTest {

    @Test
    void prints(CapturedOutput output) {
        service.run();
        assertThat(output).contains("started");
    }
}

Use the output capture for a quick check that a start-up message appears, and the appender when you need the level or the structured arguments.

System.out and System.err

java
@Test
void printsGreeting() {
    PrintStream original = System.out;
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    System.setOut(new PrintStream(buffer, true, StandardCharsets.UTF_8));
    try {
        Greeter.main(new String[] {"Ada"});
    } finally {
        System.setOut(original);
    }
    assertEquals("Hello, Ada" + System.lineSeparator(), buffer.toString(StandardCharsets.UTF_8));
}

Always restore the stream in finally. The streams are global to the JVM, so tests that redirect them must not run in parallel with others that print, or output ends up in the wrong place and both tests misbehave. Mark such tests with @Isolated, or with @ResourceLock(Resources.SYSTEM_OUT) so JUnit serialises them against other tests that declare the same resource. Compare the line separator with System.lineSeparator(), not a literal newline character, or the test fails on Windows.

Why the order of cleanup matters

A test that fails halfway must still put the global state back. Use @AfterEach, a finally block or an extension for anything that changes a static, such as the log level, the default locale or a stream. Leaked state is the most common cause of tests that pass alone and fail in the suite, or that pass on one machine and fail on CI where the order differs. The same care applies to a ListAppender: detach it, or later tests in the same JVM keep adding events to a list nobody reads, and memory grows for the length of the run.

Better designs

Code that prints directly is hard to test. Inject a PrintStream, a Writer or a small output interface and assert on that, so no global state is touched and tests can run in parallel. For logging, test the decision to log only when it is part of the requirement, such as an audit trail that regulators read. Otherwise test the result and let logging be, because a test that fails when someone improves a log message teaches the team to avoid improving log messages.

Checked exceptions and lambdas

assertThrows takes an Executable, which may throw checked exceptions, so you do not need to wrap the call in a try block. For assertDoesNotThrow, use it to make an expectation of no error explicit, and as a single-line smoke test of a method that should work. Keep the lambda small: one call, so a failure cannot be caused by setup code inside it.

Verifying that nothing was logged

Sometimes the requirement is the absence of a log line, for example no secrets in the output. Use the same appender and assert that no event contains the secret value, and run the test with the real configuration of the log pattern if the format could expose a field. This is cheaper than finding a leaked token in production logs, and it documents the rule for the next developer who adds a debug statement.

Testing exceptions thrown in other threads

An exception in a background thread does not reach the test thread. Collect it explicitly: submit the work to an executor and call Future.get(), which rethrows it wrapped in an ExecutionException, or set an uncaught-exception handler that stores the throwable. A test that starts a thread and then asserts immediately passes or fails depending on timing, so wait on a latch or the future with a timeout instead of sleeping.

Choosing what to assert

Decide which part of the behaviour is a requirement before writing the assertion. A thrown exception type and its identifying data usually are. A log line usually is not, unless it feeds an audit or an alert. Printed output is a requirement for command-line tools and not for services. Writing the test at the level of the requirement keeps it valid when the implementation changes. A test that pins an exact message, a precise log format and a call order has become a copy of the code, and it will fail for reasons that have nothing to do with a bug.

A parameterised exception test

When several inputs must be rejected for the same reason, a parameterised test keeps the cases together.

java
@ParameterizedTest
@ValueSource(longs = {-1, -100, Long.MIN_VALUE})
void rejectsNegativeAmounts(long cents) {
    assertThrows(IllegalArgumentException.class, () -> Money.of(cents, "EUR"));
}

Each value appears as its own entry in the report, so a failure names the input that was accepted by mistake.

Logging in parallel test runs

When JUnit runs tests in parallel, appenders attached to a shared logger see events from other tests. Filter by a marker or a thread name, or give each test its own logger name through the code under test.

When exceptions are the wrong design

If failure is a normal outcome, a return type may be a better design than an exception, as discussed in exceptions versus result types. Then the test is an ordinary assertion on a value. References: the JUnit assertions section of the user guide and the Logback appenders manual.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.