java - 如何为提示用户输入 int 的方法编写 Junit 测试
问题描述
我有一个方法要求用户在 1 到 7 之间选择一个数字。它使用 Scanner 类将用户输入作为 int。我看到了如何为字符串编码,但是我将如何修改它为 int 呢?我的方法是...
/** * 此方法要求玩家选择第 1-7 列。如果玩家输入一个数字
- 在这个范围之外
- 该方法将不断询问,直到输入正确的数字。该列是
- 减少一来说明
- 从 0 开始并返回的数组
- @param turn Player 哪个玩家轮到它,被要求提供一列
- @return int 列减一后返回 */
System.out.println("\n\n" + turn.getTag() + " please enter the column number, 1-7, \n" + "where you would like to drop your game piece. "); boolean colCorrect = false; int column = -1; while (!colCorrect){ if(Connect4TextConsole.in.hasNextInt()){ column = Connect4TextConsole.in.nextInt(); colCorrect = true;} else{ System.out.println("Please enter a number 1 through 7."); Connect4TextConsole.in.next();}} while(column < 1 || column > 7) { System.out.println("Please enter a number 1 through 7."); column = Connect4TextConsole.in.nextInt(); } return column - 1; // subtract one to account for array starting at zero }```
解决方案
在测试代码时,您不需要测试 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);
...
}
如果您特别想测试您的提示是否正确,那么您还可以注入一个PrintStream
for 输出并模拟它:
@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:");
}
推荐阅读
- apache-kafka - Kafka:在 Zookeeper 中存储自定义数据
- php - 使用 php 进行在线考试的问题状态
- google-compute-engine - 克隆 Google Compute 实例时为什么会出现“compute.images.get”权限错误?
- python - 在 Python 中制作 Discord Bot:为什么我的函数不起作用?
- javascript - JavaScript FileReader 从文件中获取数据
- css - 使用 React 的点击区域周围的小动画(最好只使用 CSS)
- c++ - std::call_once 抛出 std::system_error (未知错误-1)
- python - 使用 groupby 聚合 pandas 数据帧,然后使用 apply.... 但是如何将输出添加回原始数据帧?
- google-forms - 通过我的应用创建和管理 Google Form/Typeform
- random-forest - h2o 随机森林中的排列重要性