Surefire marks tests as failed when they set SecurityManager

174 Views Asked by At

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.

1

There are 1 best solutions below

1
gkephorus On

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