Reputation: 112
I'm trying to write junit tests for System.out, especially system.out.println, but even after reading through related posts, i couldn't get to the solutions.
public static void hello(){
System.out.println("Hello");
}
@Test void Test(){
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
hello();
assertEquals("Hello\n" , outContent.toString());
System.setIn(System.in);
System.setOut(originalOut);
System.setErr(originalErr);
}
It works perfectly fine when i use print instead of println and remove \n from assertEquals, but whenever i try println with \n, the test fails with
expected: <Hello
> but was: <Hello
>
org.opentest4j.AssertionFailedError: expected: <Hello
> but was: <Hello
>
which even the error message looks the same. Is there any way i can use println and pass the test? Thank you
Upvotes: 1
Views: 202
Reputation: 981
The problem is indeed the different line separators for Windows, I updated your fragment, I replaced \n
with + System.lineSeparator()
Locally on my Mac it works I expect it to be fine on Windows too with this change.
public static void hello(){
System.out.println("Hello");
}
@Test void Test(){
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
hello();
// Changed the line below
assertEquals("Hello" + System.lineSeparator(), outContent.toString());
System.setIn(System.in);
System.setOut(originalOut);
System.setErr(originalErr);
}
Upvotes: 3