We have a Groovy Script that exits with a status
of 0
when everything worked and a non-0 status
for different types of failure conditions. For example if the script took a user and an email address as arguments it would exit with a status
of 1
for an invalid user, and a status
of 2
for an invalid email address format. We use System.exit(statusCode)
for this. This works fine, but makes the the script difficult to write test cases for.
In a test we create our GroovyShell
, create our Binding
and call shell.run(script,args)
. For tests that assert failure conditions, the System.exit()
causes the JVM (and the test) to exit.
Are there alternatives to using System.exit()
to exit a Groovy Script? I experimented with throwing uncaught exceptions, but that clutters the output and always makes the status code 1.
In our test cases I have also experimented with using System.metaClass.static.invokeMethod
to change the behavior of System.exit()
to not exit the JVM, but that seems like an ugly hack.
imho System.metaClass.static.invokeMethod
looks fine. It's test, and hacking is fine here.
Also you can create your own wrapper around it, like:
class ExitUtils {
static boolean enabled = true
static exit(int code) {
if (!ExitUtils.enabled) {
return //TODO set some flag?
}
System.exit(code)
}
}
and disable it for tests.