控制台上的Java Simulate Scanner输入因多个输入而失败

时间:2019-06-29 19:12:52

标签: java java.util.scanner system.in

我正在尝试借助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,我只能在模拟输入中进行更改。

0 个答案:

没有答案