我正在尝试构建一个简单的应用,该应用具有如下的switch / case语句:
public void handleUserInput(char input){
switch(input) {
case 'L':
printBooksList();
break;
case 'Q':
System.exit(0);
default:
System.out.println("The option you chose was invalid");
}
}
我正在尝试执行此TDD,以使用JUnit和Mockito学习一些基础知识。但是我绝对不知道如何测试程序已退出。我必须创建MyApp的对象,然后传入值'Q'退出的模拟InputStream,因此以某种方式不适合模拟。即使此方法是公共方法,也不是我可以验证通过模拟调用的方法。
有人知道如何进行此操作吗?
我知道this answer,但是我没有测试静态方法,因此让另一个构造函数传入模拟出的System似乎是过大了。
这是我编写的测试,从我链接到的问题中获取答案:
@Test
public void shouldCallSystemExit() {
inputStream = new ByteArrayInputStream("X".getBytes());
testSubject = new BibliotecaApp(inputStream);
PowerMockito.mockStatic(System.class);
testSubject.handleUserInput('Q');
PowerMockito.verifyStatic();
System.exit(0);
System.out.println("If this message displays them System.exit() was mocked successfully");
}
但是,这将依赖性问题扔到了左右中间!我必须下载5个jar才能使PowerMock正常工作,但仍然需要hamcrest / SelfDescribing。这可能不对,我将以这种速度下载所有内容。
最佳答案
有几种方法可以在JUnit测试中测试System.exit()
:
用PowerMock模拟
调用一个调用System.exit()
的方法,并在测试中覆盖此方法。
使用System Rules library(对Stefan Birkner表示感谢)
原因是System.exit()
永不返回,因此控制永不返回测试。因此,您必须确保未调用实际方法。