【问题标题】:JUnit testing System.out values [duplicate]JUnit 测试 System.out 值
【发布时间】:2011-09-19 01:29:55
【问题描述】:

可能的重复:
Java, Junit - Capture the standard input / Output for use in a unit test
JUnit test for System.out.println()

我写了一段类似于下面的代码。我想对这个方法进行单元测试,现在我被困在 System.out 部分。假设用户输入的是 12。这将提示用户“号码错误,重试。”。是否可以测试此输出,或者使用 JUnit 是不可能的?

        public static int testUserInput() {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Give a number between 1 and 10");
            int input = keyboard.nextInt();

            while (input < 1 || input > 10) {
                System.out.println("Wrong number, try again.");
                input = keyboard.nextInt();
            }

            return input;
    }

提前致谢。

【问题讨论】:

标签: java unit-testing junit


【解决方案1】:

System.out 的类型为 java.io.PrintStream。如果您可以模拟或传递另一种可以将输出捕获到 StringReader 中的 PrintStream,您可以断言其值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    相关资源
    最近更新 更多