java - 控制台上的 Java 模拟扫描仪输入因多个输入而失败
问题描述
我正在尝试借助 Scanner 在 Java 控制台中模拟多个输入。我需要它们进行单元测试,但它失败的只有前几个值被正确采用,但其余的被忽略。请看下面的代码
String simulatedInput = "1\n" + "2\n" + "James\n" + "Snow\n" + "5\n" + "Mango\n" + "6\n";
InputStream in = new ByteArrayInputStream(simulatedInput.getBytes());
Scanner scanner = new Scanner(in);
int index = 0;
if (scanner.hasNextInt()) {
index = scanner.nextInt();
}
if (index != 1) {
System.out.println("#1) Should be 1");
}
if (scanner.hasNextInt()) {
index = scanner.nextInt();
}
if (index != 2) {
System.out.println("#2) Should be 2");
}
index = -1;
String value = null;
if (scanner.hasNextLine()) {
value = scanner.nextLine();
}
if (!"James".equals(value)) {
System.out.println("#3) Should be 'James' but |" + value + "|");
}
if (scanner.hasNextLine()) {
value = scanner.nextLine();
}
if (!"Snow".equals(value)) {
System.out.println("#4) Should be 'Snow' but |" + value + "|");
}
if (scanner.hasNextInt()) {
index = scanner.nextInt();
}
if (index != 5) {
System.out.println("#5) Should be 5 but " + index);
}
if (scanner.hasNextLine()) {
value = scanner.nextLine();
}
if (!"Mango".equals(value)) {
System.out.println("#6) Should be 'Mango' but |" + value + "|");
}
if (scanner.hasNextInt()) {
index = scanner.nextInt();
}
if (index != 6) {
System.out.println("#7) Should be 6 but " + index);
}
System.out.println("*** There should be the only line ***");
结果如下,测试# 1 和 2 通过,但其余部分因预期的输入而失败James
#3) Should be 'James' but ||
#4) Should be 'Snow' but |James|
#5) Should be 5 but -1
#6) Should be 'Mango' but |Snow|
#7) Should be 6 but 5
*** There should be the only line ***
请注意,我无法更改代码,因为我正在对该代码进行单元测试,所以我只能更改我的模拟输入。这可以解决吗?
对可能重复的响应
这不是重复的问题,我无法更改代码以消耗额外的 \n,我只能在模拟输入中进行更改。
解决方案
推荐阅读
- linux - 在哪里可以找到linux文件中的进程表?
- android - 如何将活动从一个显示器移动到另一个显示器
- arrays - VueJs 和 Firebase
- git - git:为什么推送进度消息经常违反直觉且无益?
- javascript - shaka 播放器从不触发“错误”监听器
- ios - 当基于场景的文档mac催化剂应用程序在应用程序重启时重新打开窗口时如何避免奇怪的行为?
- javascript - 我如何使用谷歌浏览器库 sw-appcache-behavior
- computer-science - 为什么小端机器中的二进制数被保存为这个?
- python - 循环没有得到与打印的相同的值
- javascript - 如何将 SRT 文件时间戳转换为毫秒