JUnit test for System.out.println()

前端 未结 13 1712
广开言路
广开言路 2020-11-22 03:18

I need to write JUnit tests for an old application that\'s poorly designed and is writing a lot of error messages to standard output. When the getResponse(String reque

13条回答
  •  难免孤独
    2020-11-22 03:57

    Slightly off topic, but in case some people (like me, when I first found this thread) might be interested in capturing log output via SLF4J, commons-testing's JUnit @Rule might help:

    public class FooTest {
        @Rule
        public final ExpectedLogs logs = new ExpectedLogs() {{
            captureFor(Foo.class, LogLevel.WARN);
        }};
    
        @Test
        public void barShouldLogWarning() {
            assertThat(logs.isEmpty(), is(true)); // Nothing captured yet.
    
            // Logic using the class you are capturing logs for:
            Foo foo = new Foo();
            assertThat(foo.bar(), is(not(nullValue())));
    
            // Assert content of the captured logs:
            assertThat(logs.isEmpty(), is(false));
            assertThat(logs.contains("Your warning message here"), is(true));
        }
    }
    

    Disclaimer:

    • I developed this library since I could not find any suitable solution for my own needs.
    • Only bindings for log4j, log4j2 and logback are available at the moment, but I am happy to add more.

提交回复
热议问题