ClassNotFoundException when running JUnit unit tests within Eclipse (using Maven)

I've been using Eclipse & Maven for a while now and have the m2eclipse plugin installed so that Eclipse understands the Maven dependencies. I've never had any problems running unit tests within Eclipse until recently after I update the plugin. To see if you have this problem open any unit test within Eclipse and then run it as a JUnit test (or just CTRL-F11). It is fails with a 'ClassNotFoundException ' then you have this problem.

After obtaining the classpath that Eclipse was using to spawn off the unit test it was clear that Maven (or more correctly the Maven m2eclipse plugin) was the root of the issue. It intercepts the fork operation so that it can correctly build the classpath with all the appropriate dependencies, the only thing that was missing on the classpath was any reference to the project's Java class files!

The Maven project in question has the Java source and unit test classes in sub-modules and the Maven plugin wasn't adding these sub-modules to the classpath.

Note: Back up your .project and .classpath files before you perform the steps below.

After much web searching to no avail and then much headscratching I finally found the solution tucked away in the project's Maven settings. Right-click on the project in the left-hand pane and choose 'Properties' then click 'Maven' and you should be presented with the screen below:


Tick the 'Include Modules' box, click 'Apply', agree to Maven possibly trashing your project and wait...

You should now be able to run your unit tests again as it's put all the classes within the sub-modules encapsulated by the top-level POM on the classpath. I think this option must have changed from version 0.9.4 onwards of the m2eclispe plugin as my previous version 0.9.3 didn't suffer with this issue.

Technorati Tags: , , , , , , ,

2 comments:

Eugene Kuleshov said...

Andrew, it would have been easier if instead of struggling you just asked what is happening with your project in the m2eclipse mailing list.

The "include modules" option is described on the wiki at http://docs.codehaus.org/display/M2ECLIPSE/Dependency+Management

abeacock said...

Eugene, thank you so much for posting so quickly, I did have a good search around but obviously didn't come across the page you have linked.

I have another question: have you experienced any performance problems with ticking that box?