このメソッドの単体テストを作成するのは非常に難しいことがわかりました。基本的に、ユーザーがquitコマンドを入力するとプログラムが終了します。
SytemExitクラス:
public class SystemExit {
public void exit(int status) {
System.exit(status);
}
}
私の静的メソッド:
public static void exitWhenQuitDetected() {
final SystemExit systemExit = new SystemExit();
final String QUIT = "quit";
String line = "";
try {
final InputStreamReader input = new InputStreamReader(System.in);
final BufferedReader in = new BufferedReader(input);
while (!(line.equals(QUIT))) {
line = in.readLine();
if (line.equals(QUIT)) {
System.out.println("You are now quiting the program");
systemExit.exit(1);
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
メソッドexitWhenQuitDetectedをユニットテストするのに苦労しているので、ここでは何かが正しくありません(私はモックにMockitoを使用しています)。InputStreamReaderをモックして、終了が検出されたときにSystemExit.exitメソッドが呼び出されることを確認するにはどうすればよいですか?これに光を当てていただけませんか?ありがとう。
現在取り組んでいるテストを追加しましたが、機能していません。
@Test
@Ignore
public void shouldExitProgramWhenTypeQuit() {
String quit = "quit";
SystemExit systemExit = mock(SystemExit.class);
try {
BufferedReader bufferedReader = mock(BufferedReader.class);
when(bufferedReader.readLine()).thenReturn(quit + "\n");
SomeClass.exitWhenQuitDetected();
verify(systemExit, times(1)).exit(1);
} catch (IOException e) {
e.printStackTrace();
}
}