我想测试接收用户输入并根据输入调用函数/方法的程序的mainMenu。
public void mainMenu() {
System.out.println("1. Schedule a meeting");
System.out.println("2. Book vacation dates");
System.out.println("3. Check room availability");
try {
int userInput = Integer.parseInt(inputOutput("Please enter the number that corresponds to the option that you want to proceed with."));
if (userInput >= 0 && userInput <=6) {
if (userInput == 1) {
this.scheduleMeeting();
}
if (userInput == 2){
this.scheduleVacation();
}
if (userInput == 3){
this.checkRoomAvailability();
} else {
System.out.println("Please enter a number from 0 - 6");
this.mainMenu();
}
} catch (NumberFormatException e) {
System.out.println("Please enter a number from 0 - 6");
this.mainMenu();
}
}
测试userInput我认为它会是这样的:
ByteArrayInputStream in = new ByteArrayInputStream("2".getBytes());
System.setIn(in);
但是,如果是函数调用,我将如何测试预期结果?我应该使用Mockito吗?我将如何实现它?
答案 0 :(得分:1)
1)你可以制作一个&#39; mock&#39;测试。阅读Mockito。
2)您可以传递用户的输入参数,如方法参数。
3)只需使用假值进行测试。输入您自己的整数并编写测试。您只需检查方法是否正确,并且输入此值的人无关紧要。
答案 1 :(得分:0)
您可以查看示例here
通过将IN和OUT作为参数传递,不同的方法可以使此方法更具可测性:
public static int testUserInput(InputStream in,PrintStream out) {
Scanner keyboard = new Scanner(in);
out.println("Give a number between 1 and 10");
int userInput = keyboard.nextInt();
if (userInput >= 0 && userInput <=6) {
if (userInput == 1) {
this.scheduleMeeting();
}
if (userInput == 2){
this.scheduleVacation();
}
if (userInput == 3){
this.checkRoomAvailability();
} else {
System.out.println("Please enter a number from 0 - 6");
this.mainMenu();
}
} catch (NumberFormatException e) {
System.out.println("Please enter a number from 0 - 6");
this.mainMenu();
}
return input;
}