开发者

How to test executable JAR?

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 Syste开发者_StackOverflow中文版m? 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?


Use a security police or a Security Manager that does not allow the Virtual Machine to be terminated by exit.

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

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.)


Use of AspectJ around advice could possibly work here, as you would be able to intercept the call to 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜