2015-06-18 75 views
2

我從控制檯掃描輸入的方法: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,例如,字符串和檢查異常被拋出的事實?換句話說要測試它? 我想:

IO io = mock(IO.class); 

when(io.inputValue()).thenReturn("fdas"); 

但剛剛的Mockito說,io.inputValue不能返回字符串。

回答

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 
} 
+1

這不是OP所要求的。 –

+0

我知道))))問題是我不能真正給字符串inputValue,因爲我無法通過控制檯測試它。我需要somethow命令inputValue返回不是int,但有一些錯誤來測試異常。 – ovod

+0

啊我看到了...然後我認爲你可能不得不改變輸入流從其他流中讀取。 – manouti

2

如果你想模擬從測試輸入,你可以做這樣的事情。

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

,並在inputStream對象你可以把它傳遞一個字符串,而不是爲int。

+0

如何在inputStream下放兩個值?像「fdas」和下一次0?原來拋出我的程序裏面的異常並沒有停止程序。 – ovod

+0

@ovod由於您試圖測試兩種不同的行爲,因此您應該將其分爲兩種測試方法,並且每種測試方法都應該創建自己的'InputStream'。 – Tom

0

最簡單的方法是使用Mockitos thenThrow選項來始終拋出InputMisMatchException。然後你可以通過某種方法在你自己的代碼中測試你的處理。

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