java 调测 开关_Java:如何测试调用System.exit()的方法?

事实上,

Derkeiler.com建议:

>为什么选择System.exit()?

Instead of terminating with System.exit(whateverValue), why not throw an unchecked exception? In normal use it will drift all the way out to the JVM’s last-ditch catcher and shut your script down (unless you decide to catch it somewhere along the way, which might be useful someday).

In the JUnit scenario it will be caught by the JUnit framework, which will report that

such-and-such test failed and move smoothly along to the next.

>阻止System.exit()实际退出JVM:

Try modifying the TestCase to run with a security manager that prevents calling System.exit, then catch the SecurityException.

public class NoExitTestCase extends TestCase

{

protected static class ExitException extends SecurityException

{

public final int status;

public ExitException(int status)

{

super("There is no escape!");

this.status = status;

}

}

private static class NoExitSecurityManager extends SecurityManager

{

@Override

public void checkPermission(Permission perm)

{

// allow anything.

}

@Override

public void checkPermission(Permission perm, Object context)

{

// allow anything.

}

@Override

public void checkExit(int status)

{

super.checkExit(status);

throw new ExitException(status);

}

}

@Override

protected void setUp() throws Exception

{

super.setUp();

System.setSecurityManager(new NoExitSecurityManager());

}

@Override

protected void tearDown() throws Exception

{

System.setSecurityManager(null); // or save and restore original

super.tearDown();

}

public void testNoExit() throws Exception

{

System.out.println("Printing works");

}

public void testExit() throws Exception

{

try

{

System.exit(42);

} catch (ExitException e)

{

assertEquals("Exit status", 42, e.status);

}

}

}

2012年12月更新:

Will提议in the comments使用System Rules,一个JUnit(4.9)规则的集合,用于测试使用java.lang.System的代码。

这最初由Stefan Birkner在2011年12月his answer提到。

System.exit(…)

Use the 07006 rule to verify that System.exit(…) is called.

You could verify the exit status, too.

例如:

public void MyTest {

@Rule

public final ExpectedSystemExit exit = ExpectedSystemExit.none();

@Test

public void noSystemExit() {

//passes

}

@Test

public void systemExitWithArbitraryStatusCode() {

exit.expectSystemExit();

System.exit(0);

}

@Test

public void systemExitWithSelectedStatusCode0() {

exit.expectSystemExitWithStatus(0);

System.exit(0);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值