繁体   English   中英

Junit测试println

[英]Junit test for println

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

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并通过测试吗? 谢谢

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

在我的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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM