Java单元测试从System.in中接收多个命令行输入。

huangapple go评论70阅读模式
英文:

Java UnitTest multiple command Line input from System.in

问题

我正在尝试测试一个函数,该函数会循环运行,直到输入“QUIT”,但我无法弄清楚如何从系统中模拟多行用户输入。

以下是我目前的代码:

String validStartFlow = "START-FLOW\r\nQUIT\r\n";
ByteArrayInputStream in = new ByteArrayInputStream(validStartFlow.getBytes());
System.setIn(in);
CommandLineListener cmdLineListener = new CommandLineListener(eventBus, logger);
cmdLineListener.startCommandLineListener(in);

循环运行的方法如下:

while (!userCmd.equals("QUIT")) {
    userCmd = "";
    Scanner scanner = new Scanner(in);

    while (userCmd == null || userCmd.equals("")) {
        userCmd = scanner.nextLine();
    }

    // ...
}

“START-FLOW”部分被正确读取,但在那之后当它达到scanner.nextLine()时,会崩溃并显示以下错误:

未找到行 java.util.NoSuchElementException: 未找到行

您如何使其能够从validStartFlow字符串中读取“QUIT”呢?

英文:

I'm trying to test a function that loops forever until QUIT is entered but I can't figure out how to simulate multiple lines of user input from system.

This is what I currently have

String validStartFlow = "START-FLOW\r\nQUIT\r\n";
ByteArrayInputStream in = new ByteArrayInputStream(validStartFlow.getBytes());
System.setIn(in);
CommandLineListener cmdLineListener = new CommandLineListener(eventBus,logger);
cmdLineListener.startCommandLineListener(in);

The method that loops forever is

while (!userCmd.equals("QUIT")) {
    userCmd = "";
    Scanner scanner = new Scanner(in);
    // BufferedReader reader = new BufferedReader(in);

    while (userCmd == null || userCmd.equals("")) {
        userCmd = scanner.nextLine();
    }

    ...
}

The START-FLOW is read in perfectly but then after that when it reaches scanner.nextLine() it crashes with the following error

> No line found java.util.NoSuchElementException: No line found

How can I get it to read in QUIT from the validStartFlow string?

答案1

得分: 2

你在每次迭代中都创建了一个新的Scanner,并且每次只调用了一次nextLine()

尝试将其从循环中提取出来:

Scanner scanner = new Scanner(in);
scanner.useDelimiter("\r\n");
String userCmd = "";

while (!userCmd.equals("QUIT")) {
        userCmd = scanner.nextLine();
...
英文:

You create a new Scanner on every iteration and access nextLine() only once each.

Try extracting it from the loop:

Scanner scanner = new Scanner(in);
scanner.useDelimiter("\r\n");
String userCmd = "";

while (!userCmd.equals("QUIT")) {
        userCmd = scanner.nextLine();
...

huangapple
  • 本文由 发表于 2020年10月8日 07:46:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64253811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定