如何测试可执行JAR?
我在可执行 JAR 文件中有一个简单的类:
public final class Main {
public static void main(String[] args) {
System.out.println("hello, world!");
System.exit(-1);
}
}
现在我正在尝试测试这个类/方法:
public class MainTest {
@Test public void testMain() {
Main.main(new String[] { "something" });
}
}
测试 System.exit(0)
崩溃,我可以理解为什么。现在我该怎么办?我应该模拟System
吗?这里的标准方法是什么?顺便说一句,也许我应该测试“在容器中”的方法(阅读“在 JAR 中”),就像我们使用 WAR 文件一样?
I have a simple class in executable JAR file:
public final class Main {
public static void main(String[] args) {
System.out.println("hello, world!");
System.exit(-1);
}
}
Now I'm trying to test this class/method:
public class MainTest {
@Test public void testMain() {
Main.main(new String[] { "something" });
}
}
Testing crashes on System.exit(0)
, and I can understand why. Now what should I do? Shall I mock System
? What is a standard approach here? Btw, maybe I should test the method "in container" (read "in JAR"), the same way we're doing it with WAR files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用不允许虚拟机通过
退出
终止的安全策略或安全管理器。一个可能的缺点是调用
exit
将抛出异常,请参阅java.lang.SecurityManager 和 JDK 中的权限 了解详细信息。
(我不喜欢调用
exit
的想法 - 这是一种停止虚拟机的严酷方式。)Use a security police or a Security Manager that does not allow the Virtual Machine to be terminated by
exit
.A possible drawback is that a call to
exit
will throw an Exception,See java.lang.SecurityManager and Permissions in the JDK for details.
(I do not like the idea of calling
exit
- kind of a harsh way to stop the Virtual Machine.)使用 AspectJ around suggest 可能会在这里起作用,因为您将能够拦截对 System.exit 的调用。
Use of AspectJ around advice could possibly work here, as you would be able to intercept the call to
System.exit
.你的 main 不应该调用 System.exit(0);如果没有,那没有什么区别,除非你可以在测试中调用它。
或者你不应该测试 main,因为你实际上并没有检查它所做的任何事情。
编辑:过去我建议使用 SecurityManager 来防止 System.exit() 关闭单元测试。然而,在过去的几年里,由于包括这个在内的多种原因,我只是确保不使用 System.exit() 。
Your main shouldn't call System.exit(0); if it didn't it would make no difference, except you can call it in a test.
Or you shouldn't test the main, as you don't actually check anything it does.
EDIT: In the past I have gone with the suggestion to use a SecurityManager to prevent System.exit() shutting down the unit test. However, over the last few years I have just made sure not to use System.exit() for many reasons including this one.