即使在将\ n添加到预期输出

时间:2016-04-13 14:42:27

标签: java junit

我是JUnit测试使用System.out.println()打印的函数。我取预期的输出+ \ n并将其与打印的内容进行比较,测试失败。但是,如果我从S.o.println()切换到S.o.print()并且不将换行符添加到预期输出中,它可以正常工作。该错误使得看起来可能会添加两个换行符,但添加\ n \ n也无法正常工作。

正在测试的功能:

public void printTime() {
    String h0 = "";
    String m0 = "";
    String s0 = "";
    if(hour < 10)
        h0 = "0";
    if(min < 10)
        m0 = "0";
    if(sec < 10)
        s0 = "0";

    System.out.println(h0+hour+":"+m0+min+":"+s0+sec);
}

测试:

@Test
public void testPrintTime() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));

    clock.printTime();
    assertEquals("12:00:00\n", baos.toString());
}

错误

org.junit.ComparisonFailure: expected:<12:00:00[]
> but was:<12:00:00[
]
>

1 个答案:

答案 0 :(得分:3)

如果printTime执行println,autoflush将写入缓冲的文本。这似乎已经完成了。

错误:在Windows&#34; \ r \ n&#34;可能会被测试。 尝试trim()或添加System.getProperty("line.separator")

ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos, true)); // Autoflush
clock.printTime();

assertEquals("12:00:00", baos.toString().trim());