0

I have some tests that need to check if the main code did a System.exit(...). This works very nicely with suggestions from https://stackoverflow.com/a/309427/1023341. But when running these tests in Jenkins (in stead of in my IDE Eclipse) and later when trying them on the command-line using Maven-Surefire (as Jenkins does) the tests fail without telling me why. It only tells me: Error occurred in starting fork, check output in log.

gkephorus
  • 1,232
  • 18
  • 31
  • Can you elaborate why your code is using System.exit(..) ? – khmarbaise Jul 12 '22 at 13:38
  • Thanks for your concern. I know I should not use System.exit(...) but as I'm using a legacy library that still needs migration there is currently no (cheap) way around this. (It's funny that when ever the System.exit(...) comes up that people ask this question...) – gkephorus Jul 13 '22 at 06:06
  • I would suggest to check this: https://todd.ginsberg.com/post/testing-system-exit/ – khmarbaise Jul 13 '22 at 07:49
  • Indeed, nice small little solution, though I like the lingo of https://github.com/stefanbirkner/system-lambda better. (catchSystemExit) – gkephorus Jul 13 '22 at 10:30

1 Answers1

0

When setting a SecurityManager during JUnit (5) using System.setSecurityManager and using Surefire plugin, you should restore the SecurityManager after the test.

SecurityManager origSecurityManager = System.getSecurityManager();
try {
     // ... code under test here ...
} finally {
     System.setSecurityManager(origSecurityManager);
}

or some other more suitable form. This makes sure that Maven-Surefire-plugin stays happy.

Edit for suggested pre-baked solutions:

There are two pre-baked libraries for this:

  1. junit5-system-exit
  2. system-lambda

As the name suggests: the system-lambda is a Java 8+ solution. Both are JUnit 5 compatible. My personal preference lies with the lambda solution.

More background information

gkephorus
  • 1,232
  • 18
  • 31