4

So I looked up this question and tried it, but with no success.

My code should be testing if the method is correctly outputing the text onto the console by reading it back in using Streams.

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    PrintStream myStream = new PrintStream(outStream);
    System.setOut(myStream);
    o.doSomething(); //printing out Hi
    System.out.flush();
    System.setOut(savedOldStream);//setting it back to System.out
    assertEquals(outStream.toString(),"Hi");

but everytime I run JUnit it fails. I also tried: assertTrue(outStream.toString().equals("Hi")); but this didn't work either.

This is the doSomething() method:

public void doSomething () {
    System.out.println("Hi");
}
Community
  • 1
  • 1
NhatNienne
  • 937
  • 3
  • 11
  • 20
  • 3
    What do you mean by "*didn't work*"? What actually happens? Are you getting any errors or just a failed assertion? – PM 77-1 Jun 01 '15 at 17:48
  • There is no need to re-assign the `System.out` to test this. You can pass the `ByteArrayOutputStream` to the `doSomething()` method. – M A Jun 01 '15 at 18:25

1 Answers1

9

PrintStream#println(String str) appends a newline at the end of the string. Therefore, your assertion should trim down the additional line:

assertEquals(outStream.toString().trim(),"Hi");
M A
  • 71,713
  • 13
  • 134
  • 174