JUnit asserting two Strings whether they're equal or not

和自甴很熟 提交于 2020-12-11 05:22:53

问题


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");
}

回答1:


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");


来源:https://stackoverflow.com/questions/30579868/junit-asserting-two-strings-whether-theyre-equal-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!