我正在为现有的 Java Swing 应用程序实现一些测试,以便我可以安全地重构和扩展代码而不会破坏任何东西。我从 JUnit 中的一些单元测试开始,因为这似乎是最简单的入门方法,但现在我的首要任务是创建一些端到端测试来测试整个应用程序。
我在每个测试中重新启动应用程序,方法是将每个测试方法放在一个单独的测试用例中,并在 Ant 的 junit
任务中使用 fork="yes"
选项.但是,我想作为测试实现的一些用例涉及用户退出应用程序,这导致调用 System.exit(0) 的方法之一。这被 JUnit 视为错误:junit.framework.AssertionFailedError: Forked Java VM 异常退出
。
有没有办法告诉 JUnit 以零返回码退出实际上是可以的?
最佳答案
图书馆System Rules有一个名为 ExpectedSystemExit 的 JUnit 规则。使用此规则,您可以测试调用 System.exit(...) 的代码:
public class MyTest {
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Test
public void systemExitWithArbitraryStatusCode() {
exit.expectSystemExit();
/* the code under test, which calls System.exit(...)
* with an arbitrary status
*/
}
@Test
public void systemExitWithSelectedStatusCode0() {
exit.expectSystemExitWithStatus(0);
//the code under test, which calls System.exit(0)
}
}
系统规则至少需要 JUnit 4.9。
完全披露:我是系统规则的作者。
关于java - 在 JUnit 测试中处理 System.exit(0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6141252/