Reputation: 23
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
Upvotes: 1
Views: 1038
Reputation: 4067
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, e.g.
@BeforeEach
public void setUpStreams() {
System.setOut(new PrintStream(outContent, true));
}
Upvotes: 3