首页 > 解决方案 > println 的 Junit 测试

问题描述

我正在尝试为 System.out 编写 junit 测试,尤其是 system.out.println,但即使在阅读了相关帖子之后,我也无法找到解决方案。

public static void hello(){
    System.out.println("Hello");
}


@Test void Test(){
  System.setOut(new PrintStream(outContent));
  System.setErr(new PrintStream(errContent));

  hello();

  assertEquals("Hello\n" , outContent.toString());

  System.setIn(System.in);
  System.setOut(originalOut);
  System.setErr(originalErr);
}

当我使用 print 而不是 println 并从 assertEquals 中删除 \n 时,它工作得非常好,但是每当我尝试使用 \n 的 println 时,测试都会失败

 expected: <Hello
> but was: <Hello
>
org.opentest4j.AssertionFailedError: expected: <Hello
> but was: <Hello
>

甚至错误消息看起来都一样。有什么办法可以使用 println 并通过测试吗?谢谢

标签: javajunit

解决方案


问题确实是 Windows 的不同行分隔符,我更新了你的片段,我替换\n+ System.lineSeparator()

在我的 Mac 本地上它可以工作,我希望它在 Windows 上也能通过这个变化。

public static void hello(){
    System.out.println("Hello");
}


@Test void Test(){
  System.setOut(new PrintStream(outContent));
  System.setErr(new PrintStream(errContent));

  hello();

  // Changed the line below  
  assertEquals("Hello" + System.lineSeparator(), outContent.toString());

  System.setIn(System.in);
  System.setOut(originalOut);
  System.setErr(originalErr);
}

推荐阅读