java – 在终止的代码上使用JUnit
发布时间:2020-12-15 04:09:12 所属栏目:Java 来源:网络整理
导读:参见英文答案 Java: How to test methods that call System.exit()?????????????????????????????????????15个 我正在尝试测试给定的Java应用程序,为此我想使用JUnit. 我面临的问题如下:一旦我试图测试的代码完成它的工作,它调用System.exit(),它关闭应用程
参见英文答案 >
Java: How to test methods that call System.exit()?????????????????????????????????????15个
我正在尝试测试给定的Java应用程序,为此我想使用JUnit. 我面临的问题如下:一旦我试图测试的代码完成它的工作,它调用System.exit(),它关闭应用程序.虽然它也阻止我的测试完成,因为它关闭了JVM(我假设). 无论如何都要解决这个问题,而不修改原始代码?最初我尝试从新线程启动应用程序im测试,虽然这显然没有太大的区别. 解决方法
您可以使用
System Rules:“JUnit规则集合,用于测试使用java.lang.System的代码.”
在他们的规则中,你有ExpectedSystemExit,下面是一个如何使用它的例子.我相信这是一个非常干净的解决方案. import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.Assertion; import org.junit.contrib.java.lang.system.ExpectedSystemExit; public class SystemExitTest { @Rule public final ExpectedSystemExit exit = ExpectedSystemExit.none(); @Test public void noSystemExit() { //passes } @Test public void executeSomeCodeAFTERsystemExit() { System.out.println("This is executed before everything."); exit.expectSystemExit(); exit.checkAssertionAfterwards(new Assertion() { @Override public void checkAssertion() throws Exception { System.out.println("This is executed AFTER System.exit()"+ " and,if exists,the @org.junit.After annotated method!"); } }); System.out.println("This is executed right before System.exit()."); System.exit(0); System.out.println("This is NEVER executed."); } @Test public void systemExitWithArbitraryStatusCode() { exit.expectSystemExit(); System.exit(0); } @Test public void systemExitWithSelectedStatusCode0() { exit.expectSystemExitWithStatus(0); System.exit(0); } @Test public void failSystemExit() { exit.expectSystemExit(); //System.exit(0); } } 如果您使用maven,可以将其添加到您的pom.xml: <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>com.github.stefanbirkner</groupId> <artifactId>system-rules</artifactId> <version>1.3.0</version> </dependency> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |