Tuesday, July 15, 2008

On OutOfMemoryErrors In JUnit Tests

I ran into an OutOfMemoryError while running a JUnit test in Eclipse. OutOfMemoryErrors are usually really simple to fix ... just increase the amount of memory to the JVM. This issue was a little try

So first of all, I figured JUnit would be running inside the Eclipse JVM, so I increased the memory settings in eclipse.ini to 1 Gig (from 512m).

-vmargs
-Xms1024m
-Xmx1024m
-XX:PermSize=256m
-XX:MaxPermSize=256m

I restarted Eclipse and reran the JUnit test. Same result.

I then decided to try to execute the same code in our webapp (running in Tomcat 5.5 configured with 512m of heap) and it completed successfully. This made me realize that the JUnit tests must be running in a separate JVM (either spawned or forked). The critical piece is that the JUnit JVM was not using the Eclipse memory settings from eclipse.ini. Instead, it must be using the default JVM memory settings (i.e. 64m). I searched a bit for how one might allocate more memory to a JUnit test in Eclipse and didn't find anything conclusive, so I went in and played around with the JUnit settings myself.

I started by opening up the Eclipse page that allows a user to manage JUnit configuration settings (right click a JUnit class file and select Run As > Open Run Dialog). From this dialog, click on the "Arguments" tab and paste the following settings into the "VM arguments" field:

-Xms512m
-Xmx512m

Apply the settings and Close the dialog. Rerun your test and reconfigure these settings if necessary.



6 comments:

Burke said...

Nice tip! Thanks for this blog. :-)

B-rizzle said...

Yeah, nice tip. I'm wondering if there is any way to make this the default configuration when running all unit tests so I don't have to customize this for every Unit Test that I run in Eclipse.

psable said...

Thanks!

Unknown said...

Thanks !!! that was really helpful

Mike Coleman said...

I ran into the same issue recently. Here's another option that does basically the same thing but a little quicker.

In window preferences, go to Java -> Installed JREs. Choose your default and duplicate it. Click on the duplicate, give it a name of "JRE for Junit" and set the memory settings on the Default VM Arguments.

Now, next time you run a JUnit, choose the new JRE. It saves a few key strokes instead of having to enter the JVM arguments every time, just choose the JRE from the choices presented in the debug configurations for JUnit

Justin Miranda said...

Thanks for your comment, Mike (sorry for the delay in publishing it).