Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable assertions in the Gradle run task

By default, Java disables assertions. (The test I'm using here is assert false; as the first line in main().)

I'd like to have them enabled while running my program with gradle run. What's the trick for doing this?

like image 961
rwallace Avatar asked Jan 23 '18 07:01

rwallace


People also ask

How do I enable assert?

To configure assertion options one must use either the -ea or -da command line flags to enable or disable assertions with the command line tool: “java”. For example, “java -ea Assert” where Assert is a java class file. You may also specify a specific class or package as follows.

Is assertion enabled by default?

Just remember that assertions aren't enabled by default, so never assume they will be executed when used in the code.

Can assertions be enabled for packages?

You could enable assertions for all packages, then disable them for some of the packages. Or otherwise- disable for all packages, then enable only for some of them.


2 Answers

There is a specific flag enableAssertions that you can set to enable assertions. Such flags are often more readable than working with the jvm args directly. It comes down to personal preferences I think.

Instead of working with applicationDefaultJvmArgs you can add the following to your build.gradle file:

run {
    enableAssertions = true
}

This configures the run task to enable assertions.

The run task is of type JavaExec, have a look at the documentation if you are interested in other parameters that you can set (e.g., workingDir or heapMaxSize).

like image 69
Markus Weninger Avatar answered Sep 28 '22 08:09

Markus Weninger


tasks.withType(JavaExec) {
     enableAssertions = true
}
like image 25
Marcus Vinícius Voltolim Avatar answered Sep 28 '22 07:09

Marcus Vinícius Voltolim