How to set JVM parameters for Junit Unit Tests?
Solution 1:
In Maven you can configure the surefire plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<argLine>-Xmx256M</argLine>
</configuration>
</plugin>
If you use Maven for builds then this configuration will be carried in the source tree and applied when tests are carried out. See the Maven Surefire Plugin documentation.
Solution 2:
In IntelliJ you can specify default settings for each run configuration. In Run/Debug configuration dialog (the one you use to configure heap per test) click on Defaults and JUnit. These settings will be automatically applied to each new JUnit test configuration. I guess similar setting exists for Eclipse.
However there is no simple option to transfer such settings (at least in IntelliJ) across environments. You can commit IntelliJ project files to your repository: it might work, but I do not recommend it.
You know how to set these for maven-surefire-plugin
. Good. This is the most portable way (see Ptomli's answer for an example).
For the rest - you must remember that JUnit test cases are just a bunch of Java classes, not a standalone program. It is up to the runner (let it be a standalone JUnit runner, your IDE, maven-surefire-plugin
to set those options. That being said there is no "portable" way to set them, so that memory settings are applied irrespective to the runner.
To give you an example: you cannot define Xmx
parameter when developing a servlet - it is up to the container to define that. You can't say: "this servlet should always be run with Xmx=1G
.
Solution 3:
Parameters can be set on the fly also.
mvn test -DargLine="-Dsystem.test.property=test"
See http://www.cowtowncoder.com/blog/archives/2010/04/entry_385.html
Solution 4:
According to this support question https://intellij-support.jetbrains.com/hc/en-us/community/posts/206165789-JUnit-default-heap-size-overridden-
the -Xmx argument for an IntelliJ junit test run will come from the maven-surefire-plugin, if it's set.
This pom.xml snippet
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Xmx1024m</argLine>
</configuration>
</plugin>
seems to pass the -Xmx1024 argument to the junit test run, with IntelliJ 2016.2.4.