问题描述
我正在为现有的Java Swing应用程序实现一些测试,这样我就可以安全地重构和扩展代码而不会破坏任何东西。我开始在JUnit中进行一些单元测试,因为这似乎是最简单的入门方式,但现在我的首要任务是创建一些端到端的测试以整体运行应用程序。
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.
我在每个测试中重新启动应用程序,将每个测试方法放在一个单独的测试用例中,并在Ant中使用 fork =yes
选项 junit
任务。但是,我想要作为测试实现的一些用例涉及用户退出应用程序,这导致调用System.exit(0)的方法之一。这被JUnit视为错误: junit.framework.AssertionFailedError:分叉的Java VM异常退出
。
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
.
是有一种方法告诉JUnit退出代码为零实际上是否正常?
Is there a way to tell JUnit that exiting with a return code of zero is actually OK?
推荐答案
我如何处理这是安装一个安全管理器,在调用System.exit时抛出异常。然后有代码捕获异常并且不会使测试失败。
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);
这篇关于在JUnit测试中处理System.exit(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!