Java 命令行程序和嵌套 readLine() 的 TDD
基本上,我正在编写一个 Java 命令行应用程序,它通过 readLine 接受来自用户的参数。例如,如果用户按“1”,则会询问用户要借阅哪本书,用户可以按“1”或“2”按书的编号...因此,应用程序接受用户参数两次。我也尝试使用 TDD 来测试应用程序。
问题就在这里。 如果我做这样的事情来模拟用户输入
System.setIn(new ByteArrayInputStream(PRESS_TWO.getBytes())); // set the first option
Program.main(new String[]{}); // run the program
System.setIn(new ByteArrayInputStream(PRESS_ONE.getBytes())); // set the second option
等待用户选择选项的第一步是可以的,但是它将直接执行第二步而不等待第二个输入。我如何在JUnit中模拟这个?
谢谢
这就是我读取输入的方式
try {
i1 = Integer.parseInt(reader.readLine());
}
catch (Exception e) {
System.out.println("Enter a valid integer!!");
}
if (i1 == 1) {
System.out.println(" 1. Book1 ");
System.out.println(" 2. eBook2 ");
System.out.println(" 3. Book3 ");
}
else if (i1 == 2) {
System.out.println(" Which one do you want?: ");
int i2 = 0;
try {
i2 = Integer.parseInt(reader.readLine());
}
catch (Exception e) {
// Do you know what numbers are!!!
System.out.println("Enter a valid integer!!");
}
}
Basically, I'm writing a Java Command-line application which accept parameter from user by readLine. Ex, if the user press "1" it will ask which book the user wants to check out, the user can press the number of the book by "1" or "2" ... So, the application accepts user parameter two times. And I'm trying to use TDD to test the application alongside as well.
Here is the problem.
If I do something like this to simulate user input
System.setIn(new ByteArrayInputStream(PRESS_TWO.getBytes())); // set the first option
Program.main(new String[]{}); // run the program
System.setIn(new ByteArrayInputStream(PRESS_ONE.getBytes())); // set the second option
The first step that waits for user to choose option is ok, but it will go right through the second step without waiting for the second input. How can I simulate this in JUnit?
Thanks
This is how I read input
try {
i1 = Integer.parseInt(reader.readLine());
}
catch (Exception e) {
System.out.println("Enter a valid integer!!");
}
if (i1 == 1) {
System.out.println(" 1. Book1 ");
System.out.println(" 2. eBook2 ");
System.out.println(" 3. Book3 ");
}
else if (i1 == 2) {
System.out.println(" Which one do you want?: ");
int i2 = 0;
try {
i2 = Integer.parseInt(reader.readLine());
}
catch (Exception e) {
// Do you know what numbers are!!!
System.out.println("Enter a valid integer!!");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于您的代码如何读取输入,但我假设一旦到达第一个 ByteArrayInputStream 的末尾,您的代码就会看到文件结尾并终止。尝试将两个流合并为一个(用换行符分隔)。
It depends on how your code reads the input, but I would assume that once the end of the first
ByteArrayInputStream
is reached, your code sees end-of-file and terminates. Try to combine the two streams into one (separated by a newline).