【问题标题】:How can I test a command line Java app from JUnit, without mocking?如何在不模拟的情况下从 JUnit 测试命令行 Java 应用程序?
【发布时间】:2021-11-17 06:45:16
【问题描述】:

这是我的代码:

public class Foo {
  public static void main(String... args) {
    // reconfigure global logging
    // do something else
  }
}

我如何在不模拟的情况下从 JUnit(或者可能不是)进行测试?我希望这个main() 函数完全按照它通常会做的事情,然后捕获它的控制台输出以进行断言。当然,如上所述,重新配置全局日志不会干扰其他测试。基本上,我需要一个新的 JVM 来运行它。

【问题讨论】:

  • 做到这一点。
  • 你是什么意思:'catch its console output'?
  • @Stultuske 好吧,它会在控制台打印一些东西,我想得到它并传递给 JUnit 断言进行验证

标签: java testing junit junit5


【解决方案1】:

您可以尝试在测试之前设置(实际上是模拟)System.out,例如:

public class Foo {
    public static void main(String... args) {
        System.out.print("Console output");
    }
}

测试:

@Test
public void canPrint() {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    System.setOut(new PrintStream(os));

    Foo.main();

    assertEquals("Console output", os.toString());
}

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2014-12-17
    • 2020-04-03
    • 2014-07-22
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多