我发现很难为这种方法编写单元测试,当用户键入退出命令时,它基本上会退出程序。
系统退出类:
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();
}
}
您应该包括PowerMockito http://code.google.com/p/powermock/wiki/MockitoUsage13将 Jas 放入您的项目中,而不仅仅是普通的 Mockito。 Powermock 库设计用于模拟静态和/或最终类和方法。
下列这篇博文 http://loongest.com/powermock/mock-static-void-method/包含描述与您类似的场景的示例代码。
本质上你需要一个与此类似的测试类......
@RunWith(PowerMockRunner.class)
@PrepareForTest({System.class, ClassToTest.class})
public class SystemExitTest {
@Test
public void shouldCallSystemExit() {
PowerMockito.mockStatic(System.class);
ClassToTest.methodToTest();
PowerMockito.verifyStatic();
System.exit(0);
System.out.println("If this message displays them System.exit() was mocked successfully");
}
}
鉴于这个简单的实现类......
public class ClassToTest {
public static void methodToTest() {
// do some stuff
System.exit(0);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)