Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java单元测试输入异常_Java_Unit Testing_Exception_Mocking - Fatal编程技术网

java单元测试输入异常

java单元测试输入异常,java,unit-testing,exception,mocking,Java,Unit Testing,Exception,Mocking,我有从控制台扫描输入的方法: private int chooseItem() throws IOException { return inputoutput.inputValue(); } public int inputValue() throws IOException { Scanner scanner = new Scanner(System.in); return scanner.nextInt(); } 正如您所看到的,它希望将int作为传入值,如果我输

我有从控制台扫描输入的方法:

private int chooseItem() throws IOException {
    return inputoutput.inputValue();
}

public int inputValue() throws IOException {
    Scanner scanner = new Scanner(System.in);
    return scanner.nextInt();
}
正如您所看到的,它希望将
int
作为传入值,如果我输入
String
,它应该抛出
inputmaschecxeption
。问题是,在Java中,我如何教inputValue返回smth而不是int,例如string,并检查抛出异常的事实?换言之,测试它? 我试过:


但是mockito只是说io.inputValue不能返回字符串。

您可以将
系统重定向到输入流中,以读取无效的输入:

InputStream in = System.in;
System.setIn(new ByteArrayInputStream("fdas".getBytes()));
try {
    // call inputValue method
} finally {
    System.setIn(in);  // restore old input stream
}

如果您想模拟测试中的输入,您可以这样做

InputStream inputStream = new ByteArrayInputStream( "fdas".getBytes() );
System.setIn(inputStream);

inputStream
对象中,您可以让它传递一个字符串,而不是int。

最简单的方法是使用Mockitos-thenthow选项,使inputmaschException始终被抛出。然后,您可以通过某种方法在自己的代码中测试对它的处理

when(io.inputValue()).thenThrow(new InputMismatchException());

这不是OP所要求的。我知道())问题是我不能真正将字符串赋予inputValue,因为我不能通过控制台测试它。我需要一些方法来命令inputValue返回的不是int而是一些错误来测试异常。啊,我明白了。。。然后,我想您可能需要将输入流更改为从其他流读取。如何在inputStream下放置两个值?像“fdas”和下一次0?事实证明,在我的程序中引发异常并不会停止程序。@ovod由于您试图测试两种不同的行为,您应该将其分为两种测试方法,并且每个测试方法都应该创建自己的
InputStream
when(io.inputValue()).thenThrow(new InputMismatchException());