JUnit asserting two Strings whether they're equal or not

11,039

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");
Share:
11,039
NhatNienne
Author by

NhatNienne

Updated on June 05, 2022

Comments

  • NhatNienne
    NhatNienne almost 2 years

    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");
    }
    
  • Jesper
    Jesper almost 9 years
    Writing to System.out will not write anything in the ByteArrayOutputStream.
  • NhatNienne
    NhatNienne almost 9 years
    Thank you very much! SO using System.out.print would also fix the problem?
  • M A
    M A almost 9 years
    @Jesper The OP has re-assigned System.out.
  • M A
    M A almost 9 years
    @NhatNienne Yes using print would avoid the newline.
  • M A
    M A almost 9 years
    Agree. For this case, the OP could do as you suggested: passing the output stream as param.