英文:
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();
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论