Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Not Found Exception when running JUnit test

People also ask

How do I resolve NoClassDefFoundError in JUnit?

To resolve module dependency, we use the module path. However, adding external jars in the module path does not make them available for the class loader. Hence the class loader considers them as missing dependencies and throws the NoClassDefFoundError.

What is class not found exception?

ClassNotFoundException is a checked exception which occurs when an application tries to load a class through its fully-qualified name and can not find its definition on the classpath. This occurs mainly when trying to load classes using Class. forName(), ClassLoader.

Should JUnit tests throw exceptions?

The JUnit TestRunners will catch the thrown Exception regardless so you don't have to worry about your entire test suite bailing out if an Exception is thrown. This is the best answer.


This appears to occur because only the source code is compiling when you use mvn clean compile (I'm using maven 3.1.0 so I'm not sure if it always behaved like this).

If you run mvn test, the test code will compile as well, but then it runs the tests (which may not be immediately desirable if you're trying to run them through Eclipse.) The way around this is to add test-compile to your Maven command sequence whenever you do a mvn clean. For example, you would run mvn clean compile test-compile.


I had a similar problem with my tests and found somewhere in the Web, that you have to go to Build Path in your project's properties and move Maven Dependencies above JRE System Library. That seems to have worked for me.


I faced the same problem and I was able to fix it using @slomek's answer but the issue resurfaced after that.

I finally fixed it by adding my project's output folder to the JUnit test's run configuration. Steps are:

  • Find your project's output folder from Project properties -> Java Build Path -> Default output folder
    • Usually this is <project-folder>/bin
  • Go to Run -> Run Configurations...
  • Click on the unit test's run configuration and click on the Classpath tab
  • Explicitly add your project's output folder under User Entries - even if the project is already included there
    • Click on Advanced -> Add folder to add the output folder

This issue might be due to weird project setup in Eclipse - e.g. source folder with nested maven projects imported as a single project/folder (at least that was how my project was setup).


If this problem occurs in Eclipse only, executing command Project -> Clean... on selected project may help.


After having tried everything here with no improvement, I solved my issue by just restarting Eclipse


I fixed my issue by running maven update. Right click project your project > Maven > Update Project