swalkner
swalkner

Reputation: 17379

Eclipse - java.lang.ClassNotFoundException

When trying to start my JUnit-Test out of Eclipse, I get a "ClassNotFoundException". When running "mvn test" from console - everything works fine. Also, there are no problems reported in Eclipse.

My project structure is the following:


edit: How can the class not be found? It's a simple HelloWorld-Application with no special libraries.

Here's my JUnit's run-configuration: alt text http://www.walkner.biz/_temp/runconfig.png


Testclass (but as I said; it doesn't work with a simple HelloWorld either...):

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.prognoserechnung.domain.User;
import biz.prognoserechnung.domain.UserRepository;
import biz.prognoserechnung.domain.hibernate.UserHibernateDao;

public class UserDaoTest {
/**
 * the applicationcontext.
 */
private ApplicationContext ctx = null;

/**
 * the user itself.
 */
private User record = null;

/**
 * Interface for the user.
 */
private UserRepository dao = null;

@Before
public void setUp() throws Exception {
String[] paths = { "WEB-INF/applicationContext.xml" };
ctx = new ClassPathXmlApplicationContext(paths);
dao = (UserHibernateDao) ctx.getBean("userRepository");
}

@After
public void tearDown() throws Exception {
dao = null;
}

@Test
public final void testIsUser() throws Exception {
Assert.assertTrue(dao.isUser("John", "Doe"));
}

@Test
    public final void testIsNoUser() throws Exception {
    Assert.assertFalse(dao.isUser("not", "existing"));
        Assert.assertFalse(dao.isUser(null, null));
        Assert.assertFalse(dao.isUser("", ""));
    }
}

Upvotes: 103

Views: 418437

Answers (30)

CouponCode
CouponCode

Reputation: 11

Eclipse is a confused p.o.s. You can probably look in the built jar or war and clearly see the class file is there. I've come to realize this error means that Eclipse is out of sync with the files on disk. Right-click the project and click Refresh and then try again. Usually that will fix the ClassNotFoundException startup errors.

Upvotes: 0

RangaM
RangaM

Reputation: 15

You must have pom.xml file. You will get class not found error in one more case- if any of the dependency is not resolved- means corresponding jar is not downloaded in the repository.

I had similar issue and I tried cleaning, building project multiple times but not much help.

Then there below entry for this dependency which was showing as mising, then I manually downloade it and placed in the repository.

<dependency>
            <groupId>oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>${ojdbc.verison}</version>
        </dependency>

Then, Run -> maven clean Maven -> Update projects -> select the project -> force update snapshots and update offline.

This will resolve the issue.

Upvotes: 0

user6877675
user6877675

Reputation: 1

If you are in Eclipse run time, it means that you already need to export the required packages through Manifest.MF file.

Export-Package: Name of the Package

Upvotes: 0

Carlos
Carlos

Reputation: 2923

I've come across that situation several times and, after a lot of attempts, I found the solution.

Check your project build-path and enable specific output folders for each folder. Go one by one though each source-folder of your project and set the output folder that maven would use.

For example, your web project's src/main/java should have target/classes under the web project, test classes should have target/test-classes also under the web project and so.

Using this configuration will allow you to execute unit tests in eclipse.

Just one more advice, if your web project's tests require some configuration files that are under the resources, be sure to include that folder as a source folder and to make the proper build-path configuration.

Upvotes: 201

Mr.A
Mr.A

Reputation: 41

For Hybris Project, I fixed the issue by applying below changes in Build Path. I selected Project and clicked on Apply and Close.

enter image description here

Upvotes: 0

David Ohio
David Ohio

Reputation: 1

If those don't work in eclipse try: Alt + Shift + X and you will see 5 options at the bottom right of your screen. Choose the Java Application and it'll work

Upvotes: -1

Eduardo de Lucca
Eduardo de Lucca

Reputation: 11

Well, you can solve this problem basically by creating a new project.

  1. Close the project (save the code in another folder on your computer).
  2. Create a new project (add a new final directory and do not leave the default directory selected).
  3. Remake your previous project adding the code saved before.

This happens because probably you created a project and didn't select a directory/folder or something like that. I hope had helped you!

Upvotes: 1

SATHIYA BALAKRISHNAN
SATHIYA BALAKRISHNAN

Reputation: 11

Make sure if your test class working before , but you facing issue all of sudden. then clean your project and build it again. Make sure project has been configured in build path as read above article.

Upvotes: 1

Adligo
Adligo

Reputation: 51

I suggest trying adding this to the VM arguments;

-verbose:class -verbose:module -Xdiag

Then you can debug it from Eclipse which should print out some message like;

java.lang.ClassNotFoundException: org.adligo.somewhere.Foo
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:398)
    at java.base/sun.launcher.LauncherHelper.loadMainClass(LauncherHelper.java:760)
    at java.base/sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:655)

From this you can set a breakpoint on LancherHelper.java 760 to debug the Eclipse Lanucher itself. In my case I noticed that user classpath appeared to be null, even though I have many jars in it in the Lanuch config.

Upvotes: 1

user3018906
user3018906

Reputation: 571

Enabling [x] Use temporary JAR to specify classpath (to avoid classpath length limitations) inside the Classpath tab of the Run configuration did the trick for me.

If your project is huge and you have lots of dependencies from other sibling projects and maven dependencies, you might hit the classpath length limitations and this seems to be the only solution (apart from making the directory to you local maven repo shorter (ours already starts at c:/m2)

enter image description here

Upvotes: 8

NIKHIL CHAURASIA
NIKHIL CHAURASIA

Reputation: 547

I am using gradle with eclipse and faced the same challenge today and tried a number of ways to resolve but the only way which helped me was to run command gradlew clean .

P.S. => Don't combine the "build" with the above mentioned command.

Helped me, try your luck.

Upvotes: -1

Yao Li
Yao Li

Reputation: 2286

Run project as Maven test, then Run as JUnit Test.

Upvotes: 0

Hari Krishna
Hari Krishna

Reputation: 3568

I faced the same problem, for me the issue is different. It came because some of the maven dependencies are not downloaded.

a. I went through properties -> Java Buildpath -> Maven Dependencies and identified the missed libraries. 
b. Removed the missed libraries artifacts from pom.xml
c. Downloaded the libraries and added them explicitly.

Upvotes: 0

Premraj
Premraj

Reputation: 74671

Usually this problem occurs while running java application java tool unable to find the class file.

Mostly in maven project we see this issue because Eclipse-Maven sync issue. To solve this problem :Maven->Update Configuration

Upvotes: 1

pavelb
pavelb

Reputation: 41

Go To Build Path -> Source and toggle to Yes option "Ignore Optional Compile Problems" for all source folders.

Upvotes: 0

user7639086
user7639086

Reputation: 1

I have see Eclipse - java.lang.ClassNotFoundException when running junit tests. I had deleted one of the external jar files which was added to the project. After removing the reference of this jar file to the project from Eclipse. i could run the Junit tests .

Upvotes: 0

wanfke
wanfke

Reputation: 19

I solve that Bulit path--->libraries--->add library--->Junit check junit4

Upvotes: 1

Sahitya M
Sahitya M

Reputation: 11

while running web applications Most of us will get this Exception. When you got this error you have place .class files in proper folder.

In web applications all .class files should sit in WEB-INF\Classes folder. if you are running web app in Eclipse please follow the steps

Step 1: Right click on Project folder and Select Properties Step 2: Click on "Java Build Path" you will see different tabs like "source" , "projects", "libraries" etc Step 3: select Source folder. under this you will see your project details Step 4: in the "Source" folder you will see Default Output Folder option. here you have to give the classes folder under WEB-INF. just give the path like projectname/WebContent/WEB-INF/classes the structure depends on your application please do remember here you no need to create "classes" folder. Eclipse will create it for you. Step 5: click on "OK" and do the project clean and Build. that's it your app will run now.

Upvotes: 1

Mahendra Rathod
Mahendra Rathod

Reputation: 148

JUnit 4.4 is not supported by the JMockit/JUnit integration. Only versions 4.5 or newer are supported that.

Upvotes: 0

Sai Killi
Sai Killi

Reputation: 1

Changing the order of classpath artifacts in the Java Build Path resolved it for me.

  1. Right Click on the project and go to Project Build path.
  2. Go to, Order and Export tab and move the JRE system library to after the sources.

This should fix it.

Upvotes: 0

Raju Guduri
Raju Guduri

Reputation: 1307

That means your pom.xml has unresolved issues. Open the problems view solve accordingly. Then you will be able to run the test cases successfully without encountering the classnotfoundexception.

Upvotes: -1

Eric Manley
Eric Manley

Reputation: 1119

Furthermore, DOUBLE-CHECK the eclipse "Web Deployment Assembly" dialog.

This can be found: Project Properties->Deployment Assembly.

Recently I had an eclipse plugin modify one of my web projects, and it added ~mysteriously~ added the maven test directories /src/test/java, /src/test/resources to the Deployment Assembly. UGGGG!!!

Which is why my project worked fine when I built & deployed just straight maven to tomcat, no ClassNotFoundExceptions... However, when I did the deploy through Eclipse, Whammo!! I start getting ClassNotFoundExceptions because the TestCode is getting deployed.

Eric

Upvotes: -1

Vikram
Vikram

Reputation: 2072

I had the same problem. All what I did was,

i). Generated Eclipse artifacts

mvn clean eclipse:eclipse

ii). Refresh the project and rerun your junit test. Should work fine.

Upvotes: 1

RutgerDOW
RutgerDOW

Reputation: 41

JUnit test from inside eclipse gave me also NoClassDefFoundError. Running 'mvn clean test' from command line gave me following error on several jars: invalid LOC header (bad signature) Deleting these jars from local m2 repository and running 'mvn clean test' again solved my problem.

Upvotes: 2

Hari Hara Earlapati
Hari Hara Earlapati

Reputation: 9

Deleting the project from eclipse (Not from hard disk) which in a way is cleaning the workspace and reimporting the project into eclipse again worked for me.

Upvotes: 0

snakedog
snakedog

Reputation: 367

I tried everything I read in this long post and, incredibly, what worked for me was, rather than clicking on the test class and selecting Run as JUnit test, clicking on the test method and running as JUnit test. I have no idea why?

Upvotes: 0

thSoft
thSoft

Reputation: 22660

Make sure your test launch configuration does NOT contain the following lines, OR try enabling automated Maven dependency management.

<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.maven.ide.eclipse.launchconfig.classpathProvider"/>
<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.maven.ide.eclipse.launchconfig.sourcepathProvider"/>

Upvotes: 0

cmh
cmh

Reputation: 41

I was hit with this issue also and was able to come up with a sufficient solution for my case. If your Eclipse project has a .classpath file in your project root (see it in Navigator view instead of Package Explorer view), be sure that your Maven classpathentry appears prior to your JRE Container classpathentry.

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>

If your project does not have a .classpath file, you can edit your project's Java Build Path to switch the Order and Export. If your project has the .classpath file and you only change your ordering in the Java Build Path, you will see that the ordering is not impacted and the issue will continue to occur.

And a project->clean never hurts things after you make the change.

Upvotes: 0

Gray
Gray

Reputation: 116938

I had tried all of the solutions on this page: refresh project, rebuild, all projects clean, restart Eclipse, re-import (even) the projects, rebuild maven and refresh. Nothing worked. What did work was copying the class to a new name which runs fine -- bizarre but true.

After putting up with this for some time, I just fixed it by:

  1. Via the Run menu
  2. Select Run Configurations
  3. Choose the run configuration that is associated with your unit test.
  4. Removing the entry from the Run Configuration by pressing delete or clicking the red X.

Something must have been screwed up with the cached run configuration.

Upvotes: 1

user2246725
user2246725

Reputation: 520

Tried

Link : [here][1]

Open your run configurations
Click on the jUnit-Test you want to start
go to the classpath tab
Try to add a folder (click on user entries, click on advanced, click on add folders,click on ok and search the outputfolder for your test classes(those you find under projektproperties java build path, source))

worked after

Maven 2 LifeCycle >> test

Upvotes: 1

Related Questions