首页 > 解决方案 > 如何为提示用户输入 int 的方法编写 Junit 测试

问题描述

我有一个方法要求用户在 1 到 7 之间选择一个数字。它使用 Scanner 类将用户输入作为 int。我看到了如何为字符串编码,但是我将如何修改它为 int 呢?我的方法是...

/** * 此方法要求玩家选择第 1-7 列。如果玩家输入一个数字

标签: javatestingjunit

解决方案


在测试代​​码时,您不需要测试 Java 的 API:您可以假设Scanner有效(例如)。

实现这一点的最灵活方法可能是将 aScanner注入处理用户输入的类中,然后在测试代码中模拟该扫描仪:

class InputHandler {
    private final Scanner input;

    public InputHandler(Scanner input) {
        this.input = input;
    }

    public void nextChoice() {
        int choice = input.nextInt();
        ...
    }
}

然后您的生产代码将如下所示:

InputHandler inputHandler = new InputHandler(new Scanner(System.in));

您的测试代码如下所示:

@Test void option2() {
    Scanner input = mock(Scanner.class);
    when(input.nextInt()).thenReturn(2);
    InputHandler testHandler = new InputHandler(input);
    ...
}

@Test void illegalInput() {
    Scanner input = mock(Scanner.class);
    when(input.nextInt()).thenThrow(InputMismatchException.class);
    InputHandler testHandler = new InputHandler(input);
    ...
}

如果您特别想测试您的提示是否正确,那么您还可以注入一个PrintStreamfor 输出并模拟它:

@Test
void testChoicePrompt() {
    Scanner input = mock(Scanner.class);
    PrintStream output = mock(PrintStream.class);
    InputHandler inputHandler = new InputHandler(input, output);
    inputHandler.nextChoice();
    verify(output).println("Enter choice:");
}        

推荐阅读