[java] Class Not Found Exception when running JUnit test

I am getting this error when running JUnit test in Eclipse:

Class not found com.myproject.server.MyTest
java.lang.ClassNotFoundException: com.myproject.server.MyTest
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:693)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClasses(RemoteTestRunner.java:429)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)

I've tried adding JUnit library in the classpath although I'm using maven, and the JUnit library is in the POM dependency.

I already have tried cleaning the project and created a new JUnit test case using the JUnit plugin for Eclipse, still getting the same error.

This question is related to java eclipse junit

The answer is


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


NoClassDefFoundError really means it can't initilize the class. It has nothing to do with finding the class. I got this error when calling trim() on a null String.

JUnit won't show NullPointerException. The string isn't null when running normally because I'm fetching the string from a properties file which is not availible for tests.

My advice is to remove pieces from the class until your tests start passing. Then you can determine which line is giving the error.


I had faced the same issue. I solved it by removing the external JUnit jar dependency which I added by download from the internet externally. But then I went to project->properties->build path->add library->junit->choosed the version(ex junit4)->apply.

It automatically added the dependency. it solved my issue.


For project that does not use maven : This worked for me https://ihategeek.wordpress.com/2012/04/18/eclipse-junit-test-class-not-found/

Adding the jre and project src at the bottom in Order and exports in build path


Might be you forgotten to place the Main class and Test Case class in /src/test/java. Check it Once.


It's worth mentioning as another answer that if you're using eGit, and your classpath gets updated because of say, a test coverage tool like Clover, that sometimes there's a cleanup hiccup that does not completely delete the contents of /path/to/git/repository/<project name>/bin/

Essentially, I used Eclipse's Error Log View, identified what was causing issues during this cleanup effort, navigated to the source directory, and manually deleted the <project name>/bin directory. Once that finished I went back to Eclipse and refreshed (F5) my project and the error went away.


In my case, changing the order of Maven Dependencies from Build Path configuration did not work for me. I changed its order from Run configuration.
Follow these steps:
• Go to Run -> Run Configurations...
• Click on the unit test's run configuration and click on the Classpath tab.
• check Use temporary JAR to specify classpath (to avoid classpath length limitations).
May be it is enough and your test works. You should try, so press Run button. If it did not work. Follow all previous steps again and without pressing Run button, go to the next step.
• In sub branches of User Entries move Maven Dependencies above your project or test class.
• Click Run button.


These steps worked for me.

  • Delete the content of local Maven repository.
  • run mvn clean install in the command line. (cd to the pom directory).
  • Build Project in Eclipse.

Earlier, in this case, I always did mvn eclipse:eclipse and restarted my Eclipse and it worked. After migrating to GIT, it stopped working for me which is somewhat weird.

Basic problem here is Mr Eclipse does not find the compiled class. Then, I set the output folder as Project/target/test-classes which is by default generated by mvn clean install without skipping the test and proceeded with following workaround:

Option 1: Set classpath for each test case

Eclipse ->Run ->Run Configurations ->under JUnit->select mytest -> under classpath tab->Select User Entries->Advanced->Add Folder -> Select ->Apply->Run

Option 2: Create classpath variable and include it in classpath for all the test cases

Eclipse ->Windows ->Classpath Variables ->New->[Name : Junit_test_cases_cp | path : ]->ok Then go to Eclipse->Run ->Run Configurations ->JUnit->select mytest ->under classpath tab ->Select User Entries->Advanced->Add classpath variables->Select Junit_test_cases_cp->ok->Apply->Run

This is the only thing currently working for me after trying all the suggestions online.


1- mvn eclipse:eclipse

2- project clean all projects

3- restart


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


It seems compile issue. Run project as Maven test, then Run as JUnit Test.


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


In my case I had a wrong maven directory structure.

Which should be like:

/src/test/java/ com.myproject.server.MyTest

After I fixed that - everything worked like a charm.


It can also be due to "[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?"


In my case, only next steps helped me to resolve this issue:

  1. Project->properties->Run/Debug Settings.
  2. In "Launch configurations for '.....'" select classes/projects
  3. Edit -> Classpath -> "Restore Default Entries"

Check if your project is opened as a Maven project and not just a regular Java project. Actually a no-brainer, but that is exactly the same reason why you might miss it.


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.


For me I had to put the project x/src/test/java/ at the bottom of the "order and export" in the "java build path"

enter image description here


I had the similar problem with my Eclipse Helios which debugging Junits. My problem was little different as i was able to run Junits successfully but when i was getting ClassNotFoundException while debugging the same JUNITs.

I have tried all sort of different solutions available in Stackoverflow.com and forums elsewhere, but nothing seem to work. After banging my head with these issue for close to two days, finally i figured out the solution to it.

If none of the solutions seem to work, just delete the .metadata folder created in your workspace. This would create an additional overhead of importing the projects and all sorts of configuration you have done, but these will surely solve these issue.

Hope these helps.


Making some dummy change and saving the test class can solve the problem. It will build the .class automatically


I had the same problem with a Gradle project with a test SourceSet with two resource directories.

This snippet comes from a main-module.gradle and adds a resource dir to the test SourceSet:

sourceSets {
    test {
        resources {
            srcDir('../other-module/src/test/resources')
        }
    }
}

Doing this I had two resource directories related to the test SourceSet of the project main-module:

../other-module/src/test/resources src/test/resources (relative to the main-module folder, automatically added by the java plugin)

I find out that if I had two files with the same name in both the source directories, something in the process resources stage went wrong. As result, no compilation started and for this reason no .class were copied in the bin directory, where JUnit was looking for the classes. The ClassNotFoundException disappeared just renaming one of the two files.


Pls check if you have added junit4 as dependency.

e.g

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

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).


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to junit

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to resolve Unneccessary Stubbing exception JUnit 5: How to assert an exception is thrown? How do I mock a REST template exchange? Class Not Found: Empty Test Suite in IntelliJ Unable to find a @SpringBootConfiguration when doing a JpaTest Failed to load ApplicationContext (with annotation) Example of Mockito's argumentCaptor Mockito - NullpointerException when stubbing Method Spring jUnit Testing properties file