1

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?

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
yegor256
  • 102,010
  • 123
  • 446
  • 597

3 Answers3

1

Use of AspectJ around advice could possibly work here, as you would be able to intercept the call to System.exit.

Noel M
  • 15,812
  • 8
  • 39
  • 47
1

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

user85421
  • 28,957
  • 10
  • 64
  • 87
0

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130