如何测试可执行JAR?

时间:2010-12-19 11:47:02

标签: java jar executable-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文件做的那样?

3 个答案:

答案 0 :(得分:1)

使用AspectJ around advice可能会在这里工作,因为您可以拦截对System.exit的调用。

答案 1 :(得分:1)

使用不允许虚拟机exit终止的安全警察或安全管理器。

    System.setSecurityManager(new SecurityManager() {
        @Override
        public void checkExit(int status) {
            throw new AccessControlException("exit not allowed during testing");
        }
    });

可能的缺点是对exit的调用会抛出异常,

有关详细信息,请参阅java.lang.SecurityManagerPermissions in the JDK

我不喜欢调用exit的想法 - 这是一种阻止虚拟机的苛刻方法。

答案 2 :(得分:0)

你的主要不应该调用System.exit(0);如果没有,那就不会有任何区别,除非你可以在测试中调用它。

或者你不应该测试主要,因为你实际上没有检查它做什么。

编辑:过去我已经建议使用SecurityManager来阻止System.exit()关闭单元测试。但是,在过去几年中,我确保不使用System.exit()有很多原因,包括这个原因。

相关问题