为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕莱坞森 2019-07-26 10:55:08
Java:如何测试调用System.exit()的方法?我有一些方法可以调用System.exit()某些输入。不幸的是,测试这些情况会导致JUnit终止!将方法调用放在新线程中似乎没有帮助,因为System.exit()终止JVM,而不仅仅是当前线程。是否有任何常见的处理方式?例如,我可以替换存根System.exit()吗?[编辑]有问题的类实际上是一个命令行工具,我试图在JUnit中测试。也许JUnit根本不适合这份工作?建议使用补充回归测试工具(最好是与JUnit和EclEmma完美集成的东西)。
查看完整描述

3 回答

?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

系统规则库有一个名为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);
    }}

完全披露:我是该图书馆的作者。


查看完整回答
反对 回复 2019-07-26
?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

实际上,您可以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)");}


查看完整回答
反对 回复 2019-07-26
  • 3 回答
  • 0 关注
  • 1010 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信