System.out.println / System.err.println的JUnit测试

时间:2016-03-09 10:03:16

标签: java junit system.out

我必须为应用程序编写测试,并且我试图为控制台上打印的某些内容编写juint测试。 该应用程序具有 - >

System.err.println("Username cannot be empty");

这是我到目前为止所做的:

ByteArrayOutputStream errContent = new ByteArrayOutputStream();
System.setErr(new PrintStream(errContent));
//left username empty and pressed login
assertEquals("Username cannot be empty", errContent.toString());

但我得到ComparisonFailure

expected <Username cannot be empty[]> 
but was <Username cannot be empty[
]>

//difference of next line. 

任何人都知道如何解决这个问题? 感谢。

编辑:尝试assertEquals("Username cannot be empty\n", errContent.toString());

现在我明白了:

expected <Username cannot be empty[]
> 
but was <Username cannot be empty[
]
>

1 个答案:

答案 0 :(得分:3)

您在测试中缺少的是System.err.println()最后有一个换行符。将assertEquals("Username cannot be empty", errContent.toString());更改为assertEquals("Username cannot be empty"+System.getProperty("line.separator"), errContent.toString());