简体   繁体   中英

jUnit test doesn't output anything

I am new to jUnit and I am running a test for the output of when the program is run.

My jUnit test is:

class Tests {

    private final ByteArrayOutputStream outContent = new
            ByteArrayOutputStream();


    @BeforeEach
     public void setUpStreams() {
     System.setOut(new PrintStream(outContent));
     }

    @AfterEach
     public void cleanUpStreams() {
     System.setOut(null);
     }

     @Test
     public void Test1() {
     Mobile ios = new Mobile();
     ByteArrayInputStream inContent = new 
     ByteArrayInputStream("".getBytes());
     System.setIn(inContent);
     Mobile.main(new String[0]);
     System.setIn(System.in);
     assertNotEquals("Welcome!"+System.lineSeparator(),outContent.toString());
     }
}

Part of my program is:

public class MobileApp {


    public static void main(String[] args) 
    {
        System.out.println("Welcome!");

}
}

I am expecting the test to pass as the outputs are supposed to be the same. However, after running the test, it fails as it shows that nothing has actually been outputted. I am unsure of why this is so any help is appreciated. Result Comparison after run of test

I suppose this might happen because of buffering in the PrintStream . You can pass true for an autoFlush parameter when constructing the PrintStream to fix the problem, eg

 @BeforeEach
 public void setUpStreams() {
      System.setOut(new PrintStream(outContent, true));
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM