Java:如何测试调用System.exit()的方法?

Java:如何测试调用System.exit()的方法?

我有一些方法可以调用System.exit()某些输入。不幸的是,测试这些情况会导致JUnit终止!将方法调用放在新线程中似乎没有帮助,因为System.exit()终止JVM,而不仅仅是当前线程。是否有任何常见的处理方式?例如,我可以替换存根System.exit()吗?

[编辑]有问题的类实际上是一个命令行工具,我试图在JUnit中测试。也许JUnit根本不适合这份工作?建议使用补充回归测试工具(最好是与JUnit和EclEmma完美集成的东西)。


慕莱坞森
浏览 1014回答 3
3回答

qq_遁去的一_1

库系统规则库有一个名为ExpectedSystemExit的JUnit规则。使用此规则,您可以测试调用System.exit(...)的代码:public void MyTest {     @Rule     public final ExpectedSystemExit exit = ExpectedSystemExit.none();     @Test     public void systemExitWithArbitraryStatusCode() {         exit.expectSystemExit();         //the code under test, which calls System.exit(...);     }     @Test     public void systemExitWithSelectedStatusCode0() {         exit.expectSystemExitWithStatus(0);         //the code under test, which calls System.exit(0);     }}完全披露:我是该图书馆的作者。

牧羊人nacy

实际上,您可以System.exit在JUnit测试中模拟或删除该方法。例如,您可以使用JMockit编写(还有其他方法):@Testpublic void mockSystemExit(@Mocked("exit") System mockSystem){     // Called by code under test:     System.exit(); // will not exit the program}编辑:替代测试(使用最新的JMockit API),在调用之后不允许任何代码运行System.exit(n):@Test(expected = EOFException.class)public void checkingForSystemExitWhileNotAllowingCodeToContinueToRun() {     new Expectations(System.class) {{ System.exit(anyInt); result = new EOFException(); }};     // From the code under test:     System.exit(1);     System.out.println("This will never run (and not exit either)");}
打开App,查看更多内容
随时随地看视频慕课网APP