有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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无法返回字符串


共 (3) 个答案

  1. # 1 楼答案

    可以将System.in重定向到输入流以读取无效输入:

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

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

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

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

  3. # 3 楼答案

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

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