java exit(0) final,在JUnit测试中处理System.exit(0)

I am implementing some tests for an existing Java Swing application, so that I can safely refactor and extend the code without breaking anything. I started with some unit tests in JUnit, since that seems the simplest way to get started, but now my priority is to create some end-to-end tests to exercise the application as a whole.

I am starting the application afresh in each test by putting each test method in a separate test case, and using the fork="yes" option in Ant's junit task. However, some of the use cases I would like to implement as tests involve the user exiting the application, which results in one of the methods calling System.exit(0). This is regarded by JUnit as an error: junit.framework.AssertionFailedError: Forked Java VM exited abnormally.

Is there a way to tell JUnit that exiting with a return code of zero is actually OK?

解决方案

How I deal with that is to install a security manager that throws an exception when System.exit is called. Then there is code that catches the exception and doesn't fail the test.

public class NoExitSecurityManager

extends java.rmi.RMISecurityManager

{

private final SecurityManager parent;

public NoExitSecurityManager(final SecurityManager manager)

{

parent = manager;

}

public void checkExit(int status)

{

throw new AttemptToExitException(status);

}

public void checkPermission(Permission perm)

{

}

}

And then in the code, something like:

catch(final Throwable ex)

{

final Throwable cause;

if(ex.getCause() == null)

{

cause = ex;

}

else

{

cause = ex.getCause();

}

if(cause instanceof AttemptToExitException)

{

status = ((AttemptToExitException)cause).getStatus();

}

else

{

throw cause;

}

}

assertEquals("System.exit must be called with the value of " + expectedStatus, expectedStatus, status);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值