ChatGPT解决这个技术问题 Extra ChatGPT

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.

try running mvn clean test once it will compile all the test classes
Can you please check if com.myproject.server.MyTest is there in bin folder? I mean if it is not compiled due to compile or build path error you will get this error.
are you testing one class or the whole project?
In my case running tests using Maven worked, but if I right-click on a test class and choose Run As -> JUnit Test, it reported ClassNotFoundException. I fixed it by right-clicking on the project and going to Properties -> Builders and then moving Maven Project Builder above the Java Builder

k
kryger

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 this happen once and slomek's answer worked and then this same error happened again so I had to try this as well. It works fine again now, so to be safe you may want to do both of these things.
Thanks, its worked for me. But in my case, its not worked till close and reopened the project in eclipse.
In simple words do a 'mvn clean test-compile' and then run your Junit tests in eclipse. It worked for me. Thanks.
what if that is a n ant project
s
slomek

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.


Thanks this solved my problem. The actual test was getting the class not found error when I tried to run it. I think this is probably a preferable first step before adding extra mvn build targets.
This method is described with screenshots in this post (in case the steps aren't clear from @slomek's answer above)
I could not move Maven Managed Dependencies above JRE System Library in Eclipse Mars 2, but I could right-click on the project and go to Properties -> Builders and then move Maven Project Builder above the Java Builder and it worked for me.
I tried all of the above and it didn't work, I also could not move the Maven Dependencies about JRE System Library but that was under the Libraries tab. Then I went to Build Path -> Order & Export -> as was able to move Maven Dependencies above JRE System library. Then I built the project and ran a Maven install, then the test ran successfully.
In my case, changing the order of Maven Dependencies from Build Path configuration did not worked for me. I changed its order from Run configuration. it worked. For those steps read my answer.
C
Community

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 /bin

Usually this is /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

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


Thank you so much; I had this problem. Your fix worked for me; the top two didn't. Up-voted.
Absolutely brilliant! Been scratching my head for ages over this. Thanks!
Thank you so much. I could never fix this myself. Mine is an Ant Project though, your solution works.
j
johanwannheden

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


Thanks - it actually worked for me - JAVE EE eclipse gradlew
Ensure we select particular project while cleaning, not all.
B
Berit Larsen

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


A
Azianese

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


This is what I do all the time and it resolves the issue..
I
ITisha

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.


R
Roman Romaniuk

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

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


Thanks!! Only this one helped me!!
N
Nayan

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.


As a note...doing this will require you to rebuilt your environment. So while it can solution just be aware of what you are about to do...
A
Aakash Goyal

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.


j
jmajcan

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.


S
Shadyar

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.


J
Jake Graham Arnold

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.


T
Toumi

1- mvn eclipse:eclipse

2- project clean all projects

3- restart


B
Blake Neal

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.


W
William

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?"


D
David Obber

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.


Y
Yao Li

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


G
Groot

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


I
Ishan Liyanage

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>

f
fayabobo

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"

https://i.stack.imgur.com/oYv4y.png


B
Ben

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.


j
jmajcan

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.


L
Lorenzo Lerate

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


S
Sathya

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


java.lang.ClassNotFoundException comes when class is already compiled but on run time due to classpath not set properly.

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now