JUnit test for System.out.println()

前端 未结 13 1705
广开言路
广开言路 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:49

    Full JUnit 5 example to test System.out (replace the when part):

    package learning;
    
    import static org.assertj.core.api.BDDAssertions.then;
    
    import java.io.ByteArrayOutputStream;
    import java.io.PrintStream;
    import org.junit.jupiter.api.AfterEach;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    
    class SystemOutLT {
    
        private PrintStream originalSystemOut;
        private ByteArrayOutputStream systemOutContent;
    
        @BeforeEach
        void redirectSystemOutStream() {
    
            originalSystemOut = System.out;
    
            // given
            systemOutContent = new ByteArrayOutputStream();
            System.setOut(new PrintStream(systemOutContent));
        }
    
        @AfterEach
        void restoreSystemOutStream() {
            System.setOut(originalSystemOut);
        }
    
        @Test
        void shouldPrintToSystemOut() {
    
            // when
            System.out.println("example");
    
            then(systemOutContent.toString()).containsIgnoringCase("example");
        }
    }
    

提交回复
热议问题