amaidment amaidment - 1 year ago 580
Java Question

How to set JVM parameters for Junit Unit Tests?

I have some Junit unit tests that require a large amount of heap-space to run - i.e. 1G. (They test memory-intensive functionality for a webstart app that will only run with sufficient heap-space, and will be run internally on Win 7 64-bit machines - so redesigning the tests isn't a practical suggestion.)

I am developing in Intellij IDEA, so I know I can set the JVM parameters (e.g. -Xmx1024M) for the test class. However, this is only for running the whole test class - if I want to run an individual test, I have to recreate the run congfigurations for that test method.

Also, those are IDE and box specific - so if I switch boxes (I develop on multiple machines) or one of my colleagues tries to run the tests, those settings are not transferred. (Also, other IDEs like Eclipse and NetBeans are used by my colleagues.) FWIW, we're using mercurial for source code control.

For the build cycle, we're using Maven, so I know how to specify the JVM parameters for that.

- I'm looking for a way of specifying the JVM parameters that will apply for the whole test class and the individual test methods; and
- I'd like to share those specification across IDEs on any machine (having picked up the code from the repository).

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download