java单元测试输入异常
我有一种扫描控制台输入的方法:
private int chooseItem() throws IOException {
return inputoutput.inputValue();
}
public int inputValue() throws IOException {
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
正如您所看到的,它希望获得int
作为传入值,如果我输入String
,它应该抛出InputMismatchEcxeption
。问题是,在Java中,我如何教inputValue返回smth而不是int,例如string,并检查抛出异常的事实?换句话说,是为了测试它?
我试过:
IO io = mock(IO.class);
when(io.inputValue()).thenReturn("fdas");
但莫基托只是说。inputValue无法返回字符串
# 1 楼答案
可以将
System.in
重定向到输入流以读取无效输入:# 2 楼答案
如果你想模拟测试中的输入,你可以这样做
在
inputStream
对象中,可以让它传递一个字符串,而不是int# 3 楼答案
最简单的方法是使用Mockitos thenthow选项,使InputMissmatchException始终被抛出。然后,您可以通过某种方法在自己的代码中测试对它的处理