Class Not Found Exception when running JUnit test
Asked Answered
S

25

143

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.

Smithsonite answered 8/7, 2012 at 6:6 Comment(6)
try running mvn clean test once it will compile all the test classesHayrick
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.Snare
are you testing one class or the whole project?Sharpshooter
Possible duplicate of Eclipse - java.lang.ClassNotFoundExceptionErde
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 BuilderSturges
Judging from other answers (solved by clean/rebuild, restarting Eclipse, making some dummy change, delete the .metadata folder, change order of classpath items, restoring defaults) and my own experience, this is some kind of race condition bug in Eclipse, even in 2023. In my case it could not find a resource file: java.io.FileNotFoundException: class path resource [foo/appStuff.xml] cannot be opened because it does not exist Then after fiddling around it suddenly started to work. With same settings as before.Franckot
C
151

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.

Clint answered 21/7, 2013 at 2:58 Comment(4)
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.Gilbreath
Thanks, its worked for me. But in my case, its not worked till close and reopened the project in eclipse.Shielashield
In simple words do a 'mvn clean test-compile' and then run your Junit tests in eclipse. It worked for me. Thanks.Papilloma
what if that is a n ant projectBivalve
P
120

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.

Polka answered 14/11, 2012 at 9:5 Comment(5)
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.Gilbreath
This method is described with screenshots in this post (in case the steps aren't clear from @slomek's answer above)Gar
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.Sturges
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.Augite
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.Mornings
G
33

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

Gar answered 21/11, 2014 at 13:34 Comment(3)
Thank you so much; I had this problem. Your fix worked for me; the top two didn't. Up-voted.Dexterous
Absolutely brilliant! Been scratching my head for ages over this. Thanks!Pindus
Thank you so much. I could never fix this myself. Mine is an Ant Project though, your solution works.Fernandes
T
19

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

Touraine answered 4/3, 2016 at 6:57 Comment(2)
Thanks - it actually worked for me - JAVE EE eclipse gradlewAramen
Ensure we select particular project while cleaning, not all.Corot
D
15

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

Defeatist answered 28/9, 2015 at 7:40 Comment(0)
I
13

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

Indiscriminate answered 30/9, 2019 at 19:47 Comment(1)
This is what I do all the time and it resolves the issue..Languor
V
5

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.

Vashtee answered 6/10, 2015 at 15:47 Comment(0)
N
3

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"
Neutrophil answered 1/6, 2016 at 13:37 Comment(1)
Thanks!! Only this one helped me!!Parasiticide
J
2

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

Jotting answered 12/8, 2019 at 22:10 Comment(0)
M
2

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.

Mornings answered 22/9, 2020 at 4:2 Comment(0)
T
1

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.

Truscott answered 8/4, 2014 at 8:20 Comment(0)
J
1

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.

Jariah answered 31/7, 2014 at 7:11 Comment(1)
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...Bwana
P
1

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.

Parachronism answered 11/1, 2019 at 20:9 Comment(0)
A
1

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

Applicable answered 26/11, 2020 at 13:57 Comment(0)
C
0

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.
Cooperative answered 3/3, 2015 at 10:10 Comment(0)
M
0

1- mvn eclipse:eclipse

2- project clean all projects

3- restart

Monterrey answered 9/4, 2015 at 11:56 Comment(0)
O
0

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.

Orthopedics answered 4/5, 2017 at 14:32 Comment(0)
M
0

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

Mashhad answered 18/9, 2017 at 21:15 Comment(0)
M
0

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.

Mustee answered 18/5, 2018 at 9:50 Comment(0)
R
0

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

Receptive answered 11/10, 2019 at 18:57 Comment(0)
S
0

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>
Spitler answered 23/12, 2019 at 11:59 Comment(0)
F
-1

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.

Fraley answered 7/7, 2017 at 10:7 Comment(0)
F
-1

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.

Fennessy answered 16/4, 2019 at 10:48 Comment(0)
D
-1

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

Decuple answered 27/6, 2019 at 6:51 Comment(0)
M
-6

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

Mineralize answered 22/8, 2014 at 9:42 Comment(1)
java.lang.ClassNotFoundException comes when class is already compiled but on run time due to classpath not set properly.Somerville

© 2022 - 2024 — McMap. All rights reserved.