JUNIT Test class in Eclipse - java.lang.ClassNotFoundException - java

I'm trying to run my junit test (to verify that a properties file loads correctly) but
I get ClassNotFoundException although the class is there and all required libraries are there too.
Here it is the error I get :
Class not found ConfigurationManagerTest java.lang.ClassNotFoundException: ConfigurationManagerTest
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
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)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
any ideas on how to fix this ?
Thanks.

ConfigurationManagerTest is not being found on your classpath. Ensure that the ConfigurationManagerTest.class file is available on your classpath.
It might not exist if it wasn't successfully compiled or if it's being created in a directory that you haven't told the Eclipse project should be on the classpath.
Assuming that you've put your test classes in a separate folder, make sure that it shows up in the "Package Explorer" view (rather than the "Navigator" view).
Under the project properties, "Java Build Path" and the "Source" tab, you can also see if the source folder is included for building as well as where the .class files are generated.

There is one more possibility. I had the same problem just now and no one of the solutions here helped. Except removing and recreating of the project - I didn't want to try it. What did help, was to clean the project two times immediately one after another! Clean + build could be repeated any number of times - it won't help. Only clean+clean and after that build goes OK. (Eclipse 3.6). Of course, you should disable autobuild for that.
Edit: This post has got its last plus on 15.11.2017. So, the problem (and the solution) remains actual.

Another possible problem is a missing builder (it will prevent from your .class file from being built).
Check that your .project file has the following lines
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>

This happened to me when I was dragging and dropping test classes to different packages. I just did the following
Saved the class in a text editor.
Deleted the offending class from eclipse project explorer.
Re-created the class.
Bingo! I can now run the test!

I had this problem and it was kind of tricky to realise what was wrong. The project had a dependency project with some error, which stopped the build from execute. When I remove this dependency problem, the project was built as expected.
Ps.: I am working on a project that has many compilation errors, because we are porting an application that was converted from Delphi to Java, so I didn't care to the compilation error at the beginning, that's why it took me some time to find out the problem.

check properties->java build path -> libraries. there should be no errors, in my case there was errors in the maven. once I put the required jar in the maven repo, it worked fine

I tried all the answers described here but none worked, but found this thread where slomek solves the problem in a very easy manner. Just go to project -> properties --> java build path. Then move Junit to the top by hitting the up bottom to the right. Then everything compiles just fine.

I tried everything mentioned here and in other posts. Some of the solutions that people proffered were:
Change the output folder for the test
Create a custom builder for the project that would run test-compile from Maven
Move the Maven dependencies higher in the Order and Export list in the project build path
There were many, many more but the one that I found to work was as follows: Close the development environment. Delete the jars used by the project from my local Maven repository. Open the IDE. Build the project. Run the test.
After hours of beating my head against my keyboard and following suggested solutions, this one worked!

what worked for me is to remove the runconfiguration of the test. Then right click the testclass and click run as junit test.
now it recreates a correct run config for me.

Another way that this can unfold, and just did for me, is if you have a build error that Eclipse doesn't tell you about. If compiling the unit test fails then there is no .class file and you will get the ClassNotFoundException.
In my case there was a missing 3rd party jar file. When I ran the test I got a pop-up window that said "Errors exist in required project(s)". I work with a huge project and I always get that message because some of the source is not available to eclipse (long story). Also it doesn't say what the errors are. So I click "Continue" and then I get the exception.
Once I realized what was going on it was easy to fix by adding the missing jar to the classpath under Run -> Debug Configurations...
I'm not sure how to best detect or prevent this from happening except to be aware of this possibility when something goes wrong and to review your most recent changes for what might have gone wrong.

I also faced similar issue as mention in comment below.
**org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:766)**
Check all mention possibility above but still could not find root cause why test case not getting execute.
Then I found that there is one package issue in my class. So due to that I was getting compilation error in my Test class.
Reason is quite simple, Due to compilation error class did not compile and could not create class file.
I fixed that compilation error and executed that Test class and its run successfully.

Are you sure your test class is in the build folder? You're invoking junit in a separate JVM (fork=true) so it's possible that working folder would change during that invocation and with build being relative, that may cause a problem.
Run ant from command line (not from Eclipse) with -verbose or -debug switch to see the detailed classpath / working dir junit is being invoked with and post the results back here if you're still can't resolve this issue.

A variation on Guy's answer above, involving additional builders. Say you have an Ant builder configured:
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value><project>/.externalToolBuilders/myprojectantlaunch.launch</value>
</dictionary>
</arguments>
</buildCommand>
</buildSpec>
If the Ant build and Eclipse build have differing output locations, Eclipse may not be able to locate the test class on the classpath. In the case of an Ant builder, also check the configured targets for clean, auto, manual and after-clean builds, to ensure that the target which builds the unit tests is called.

I add this answer as my solution review from the above.
You simply edit the file .project in the main project folder. Use a proper XML Editor otherwise you will get a fatal error from Eclipse that stats you can not open this project.
I made my project nature Javaby adding this <nature>org.eclipse.jdt.core.javanature</nature> to <natures></natures>.
I then added those lines correctly indented <buildCommand><name>org.eclipse.jdt.core.javabuilder</name><arguments></arguments></buildCommand> to <buildSpec></buildSpec>.
Run as JUnit ... Success

Right click the project in the Explorer: Build Path -> Order and Export -> Select JRE System Library [jdk] and click Bottom button.

Yet another variation.
Somehow, my formerly working test classes appeared to be running from some other location; my edits would not execute when I ran the tests.
I found that the output folder for my ${project_loc}src/test/java files was not what I expected. It had inadvertently been set to ${project_loc}target/classes.
I set it properly in project properties, Java Build Path, Source tab.

If you have a maven project try to run:
mvn clean compile
and then in eclipse clean & build your project.

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.

In "Package Explorer" view, Right click your test class, then "Build Path">>"Include", it should be OK.

I too faced the same exception, none of the solutions over internet helped me out.
my project contains multiple modules. My Junit code resides in Web module. And it's referring to client module's code.
Finally , I tried :
Right click on (Web module) project -->build path--> source tab--> Link source --> added the src files location (Client module's)
Thats it! It worked like a charm
Hope it helps

I received this error because I had recently created a new workspace and my "Installed JREs" were not set up correctly. Make sure in Preferences -> Java -> Installed JREs
the root folder of your JDK is selected. The default for me in a new workspace was a JRE for some reason.

I know this has been already answered a long time ago but the answer didnt fix it for me but, I just removed everything from the sources in the buildpath settings and re-added them

I had this problem, in my case the problem relies in the compilation, I am using maven and test classes didn't compile.
I fixed it by doing a maven install (it compiles all the files), also you can check for other reasons, that avoid test to compile like if your "run configurations" is skipping the tests to save time.

Assumming you tried everything reasonable (delete target, refresh, clean, rebuild, maven install...) and that you realized that Eclipse does not behave reasonable...
Now: Check if there is no errors suggesting it can be a plugin (any plugin) that has something to do with tests.
In my case:
I removed EclEmma.
It started working...
Spent few hours on trying to guess it!.

Please make sure the output folder in Java Build Path tab set as like below,which would determine where the .class file are generated.Then clean the project.

The above mentioned solutions didn't work for me.
I just restarted my IDE by closing it and reopening it.
And then error disappeared and its working fine now.

You may need to do a combination of the above to resolve this problem. I normally get this error when I do
mvn clean install
and see a compile error preventing the my tests from fully compiling.
Assuming the issues resolved by the above have been dealt with, try clicking Project, Clean, and clean the project which contains the test you want to run. Also make sure Build Automatically is checked.

Related

Cannot resolve symbol - IntelliJ [duplicate]

This problem happens intermittently for different libraries and different projects.
When trying to import a library, the package will be recognized, but the class name can't be resolved.
If on the import statement, I right-click -> Goto -> the package's declaration, I see all the decompiled classes displayed in the side pane -- Including the ones I need --
If I try to auto-complete the import statement, I notice the class I need is not featured in the dropdown.
I tried invalidating caches already, doesn't work. I cannot find any class conflicts -- there is no other jar file in my classpath with the same package name.
I am able to import this class into other projects.
Please see screen shots:
Anyone have a clue?
You can try invalidating the cache and restarting IntelliJ, in many cases it will help.
File -> Invalidate Caches/Restart
There can be multiple reasons for this. In my case it was wrong source root issue. Invalidate caches didn't work along with other solutions.
Check your module source roots.
Project Structure (Ctrl+Alt+Shift+S).
Modules
Select your problem module.
Change tab on top of window "Sources".
Remove unwanted source roots. Keep one and add src and test source roots in this root.
File -> Invalidate Caches/Restart
And
Build your project
IntelliJ has issues in resolving the dependencies.
Try the following:
Right click on pom.xml -> Maven -> Reimport
Again Right click on pom.xml -> Maven -> Generate sources and update folders
Run this command in your project console:
mvn idea:idea
Done.
Had this issue many times. Tried 'Invalidate Cache & Restart' and all other solutions. Running that command works perfect to me.
I'm currently using IntelliJ 2019.2, but this also happened in previous versions and solution worked as well.
File -> Invalidate Caches/Restart or rebuilding the project did not work wor me.
What worked for my Gradle project was to "Refresh all Gradle projects" from the Gradle tab on top-right corner of IntelliJ v2017, using the yellow marked button shown below:
Check your module dependencies.
Project Structure (Ctrl+Alt+Shift+S).
Modules
Select your problem module.
Change tab on top of window "Dependencies".
Check what needed library (maybe, you need to add specified library
in the tab 'libraries') or module has listed here and it has right
scope ('complile' mostly).
I faced a similar issue, Mike's comment helped me move in the direction to solve it.
Though the required library was a part of the module in my project too, it needed a change of scope. In the module dependency, I changed the scope to "Compile" rather than "Test" and it works fine for me now.
Had the same problem till I noticed that the src folder was marked as root source instead of java!
Changing to only the java (src/main/java) to be the source root solved my problem
I found the following answer from #jossef-harush and #matt-leidholm useful from another link
in IntelliJ editor, click on the red keyword (Integer for example) and press ALT + ENTER (or click the light bulb icon)
select Setup JDK from the intentions menu
click on Configure
In my case, the JDK path was incorrect (pointed on /opt/jdk1.7.0_51 instead of /opt/jdk1.7.0_65)
click on the ... and browse to the right JDK path
let's clear the cache
Right click on pom.xml file, go to Maven click on Reimport. I had similar problem and this worked for me.
After a long search, I discovered that a dependency was somehow corrupted on my machine in a maven project. The strange thing was that the dependency was still working correctly in the compiled java code. When I cleaned and rebuilt my maven dependency cache however, the problem went away and IntelliJ recognized the package. You can do this by running:
mvn dependency:purge-local-repository
Intrestingly, the source of my problem hence wasn't IntelliJ, but maven itself.
For 2020.1.4 Ultimate edition, I had to do the following
View -> Maven -> Generate Sources and Update Folders For all Projects
The issue for me was the libraries were not getting populated with
mvn -U clean install from the terminal.
Try cleaning maven from upstream by:
mvn -U clean install
I also got this error for multiple times when I try to build a new java project.
Below is the step how I got this stupid issue.
Create an empty project, and create new directory src/main/java.
Create the source package net.gongmingqm10.sketch.
Use gradle wrapper, gradle idea to build the gradle stuff for the project.
Add some dependencies in build.gradle file, and gradle build, reimport the project.
Create User.java and School.java in the existing package net.gongmingqm10.sketch
I got the error while I try to use import School in User.java.
Intellij keeps complain can not resolve symbol on import.
Solution:
Build the project first, and mark the main/java as the source root. Create a new directory with the same name net.gongmingqm10.sketch. Move all the files from the old troubling packages to new package.
Root cause:
Directory tree of source code
As you can see from the tree. I got a directory named net.gongmingqm10.sketch. But what we really need is the 3 levels directory: net->gongmingqm10->sketch
But before I finish building my project in Intellij, I create new directory named net.gongmingqm19.sketch, which will give me a real directory with the name net.gongmingqm10.sketch.
When we trying to import it. Obviously, how can intellij import the file under the weired directory with the name a.b.c.
#Anton Dozortsev I was driven crazy by a similar behavior; I ended up re-installing the IDE a bunch of times, only getting past the issue after removing the IDEA app, all caches, preferences, etc.
I tried all kinds of steps in the interim, (like restarts, invalidations, deleting .idea and *.iml files, and others.)
Turns out, the problem was due to IntelliJ's idea.max.intellisense.filesize setting. I had set it to 100KB, which was smaller than my dependency's size, leading to IntelliJ showing it as unknown, just like in your screenshot.
Fix:
Click on Help -> Edit Custom Properties
Set the property to a larger value; the default is 2500KB
idea.max.intellisense.filesize=2500
Please try File-> Synchronize. Then close and reopen IntelliJ before you invalidate.
Once I restarted. I would have invalidated but the synchronize cleared everything after restarting.
Simple Restart worked for me.
I would suggest first try with restart and then you may opt for invalidating the cache.
PS : Cleaning out the system caches will result in clearing the local history.
I found the source cause!
In my case, I add a jar file include some java source file, but I think the java source is bad, in Intellij Idea dependency library it add the source automatic, so in Editor the import is BAD, JUST remove the source code in "Project Structure" -> "Library", it works for me.
What did it for me is to edit the package file in the .idea folder as I accidentally added sources to this jar library and android couldn't resolve it by deleting the sources line as marked in the b/m picture library error.
Then rebuild the gradle and bam problem solved.
I had the same issue and the reason for that was incorrect marking of the project's sources.
I manually created the Root Content and didn't notice that src/main/test folder was marked as Sources instead of Tests. So that is why my test classes were assumed to have all their test libraries (JUnit, Mockito, etc.) with the scope of Compile, not Test.
As soon as I marked src/main/test as Tests and rebuilt the module all errors were gone.
I had this recently while trying to use Intellij to work on NiFi, turned out the issue was that NiFi requires Maven >= 3.1.0 and the version that I'd checked out with (I guess my default) was 3.0.5. Updating the Maven version for the project fixed it, so in some cases Maven version mis-alignment can be a thing to look...I'd guess it's fairly unusual but if you get this far on the thread you're probably having an unusual issue :)
file-> Project Structure -> Modules, find the module with problems, click it and choose the Dependencies tab in the right side. Click the green plus sign, try to add the jar or libraries that cause the problem. That works for me.
Nothing I tried above worked for me (not that I tried every suggestion). What finally did the trick was to rename the class -- I just added a 2 to the class name and filename. Then I resolved all the references manually. (Since they weren't recognized, the refactoring did not change the references automatically.)
Once the "2-version" was happily resolved everywhere, I was then able to refactor and remove the 2 from the class and file, and everything was then as it should be.
in my case the solution was to add the project as maven project, besides the fact that i imported as maven project :P
go to pom.xml -> right click -> add as maven project
My issue was my Maven plugin got disabled after an update. I went to Help -> Find Action... -> Typed in Maven and found that it was "Off". I clicked the toggle switch and after a bit of loading it was re-enabled.
Also, check your class is not in compile exclusions
If you see, that there is a little grey cross in left top corner, you must remove class from compile exclusions
How to remove
Old question, '21 response. I ran into the issue where my go build would build code successfully but my Goland IDE showed missing modules or dependencies. I tried Invalidating Caches and Restart, but had the same problem. From another S/O thread, I tried adding the GO111MODULE=on to my Path Variables, but that didn't resolve the IDE problems either.
What worked for me was picking the correct GOROOT path in Preferences > Go > GOROOT.
I had two versions of go installed, one by brew and one from the online Go installer. I selected the brew install path, and my IDE was able to resolve the dependencies properly.
I've tried all the complicated methods and they didn't work, since I was too lazy to re-import the project I tried something else.
Mine is a gradle project, so I went to my gradle.build file, removed the dependency, refreshed the dependencies, then added the dependency again and refreshed again, the imports started working after that.
Faced similar issue,
I Updated Intellij and error start coming - Can't Resolve Symbols.
Went to Plugins, Updated the plugins & Restart
Problem Solved !!

Command works in terminal but not with java [duplicate]

What are the possible causes of a "java.lang.Error: Unresolved compilation problem"?
Additional information:
I have seen this after copying a set of updated JAR files from a build on top of the existing JARs and restarting the application. The JARs are built using a Maven build process.
I would expect to see LinkageErrors or ClassNotFound errors if interfaces changed. The above error hints at some lower level problem.
A clean rebuild and redeployment fixed the problem. Could this error indicate a corrupted JAR?
(rewritten 2015-07-28)
Summary: Eclipse had compiled some or all of the classes, and its compiler is more tolerant of errors.
Long explanation:
The default behavior of Eclipse when compiling code with errors in it, is to generate byte code throwing the exception you see, allowing the program to be run. This is possible as Eclipse uses its own built-in compiler, instead of javac from the JDK which Apache Maven uses, and which fails the compilation completely for errors. If you use Eclipse on a Maven project which you are also working with using the command line mvn command, this may happen.
The cure is to fix the errors and recompile, before running again.
The setting is marked with a red box in this screendump:
try to clean the eclipse project
you just try to clean maven by command
mvn clean
and after that following command
mvn eclipse:clean eclipse:eclipse
and rebuild your project....
Your compiled classes may need to be recompiled from the source with the new jars.
Try running "mvn clean" and then rebuild
The major part is correctly answered by Thorbjørn Ravn Andersen.
This answer tries to shed light on the remaining question: how could the class file with errors end up in the jar?
Each build (Maven & javac or Eclipse) signals in its specific way when it hits a compile error, and will refuse to create a Jar file from it (or at least prominently alert you). The most likely cause for silently getting class files with errors into a jar is by concurrent operation of Maven and Eclipse.
If you have Eclipse open while running a mvn build, you should disable Project > Build Automatically until mvn completes.
EDIT:
Let's try to split the riddle into three parts:
(1) What is the meaning of "java.lang.Error: Unresolved compilation
problem"
This has been explained by Thorbjørn Ravn Andersen. There is no doubt that Eclipse found an error at compile time.
(2) How can an eclipse-compiled class file end up in jar file created
by maven (assuming maven is not configured to used ecj for
compilation)?
This could happen either by invoking Maven with no or incomplete cleaning. Or, an automatic Eclipse build could react to changes in the filesystem (done by Maven) and re-compile a class, before Maven proceeds to collect class files into the jar (this is what I meant by "concurrent operation" in my original answer).
(3) How come there is a compile error, but mvn clean succeeds?
Again several possibilities: (a) compilers don't agree whether or not the source code is legal, or (b) Eclipse compiles with broken settings like incomplete classpath, wrong Java compliance etc. Either way a sequence of refresh and clean build in Eclipse should surface the problem.
I had this error when I used a launch configuration that had an invalid classpath. In my case, I had a project that initially used Maven and thus a launch configuration had a Maven classpath element in it. I had later changed the project to use Gradle and removed the Maven classpath from the project's classpath, but the launch configuration still used it. I got this error trying to run it. Cleaning and rebuilding the project did not resolve this error. Instead, edit the launch configuration, remove the project classpath element, then add the project back to the User Entries in the classpath.
I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.
Just try to include package name in eclipse in case if you forgot it
Import all packages before using it, EX: import java.util.Scanner before using Scanner class.
These improvements might work and it will not give Java: Unresolved compilation problem anymore.
Also make sure to check compiler compliance level and selected jdk version is same
As a weird case, I encountered such an exception where the exception message (unresolved compilation bla bla) was hardcoded inside of generated class' itself. Decompiling the class revealed this.
I had the same issue using the visual studio Code. The root cause was backup java file was left in the same directory.
Removed the backup java file
When the build failed, selected the Fix it, it cleaned up the cache and restarted the workSpace.

Netbeans compiles fine but show errors in editor

Netbeans is not importing a jar from another project. The classpath is fine, the project compiles fine but the editor show several errors in project because it cannot locate classes inside that jar. I've already rebuilded the projects and clean Netbeans' cache (~/.netbeans/7.1.1/var/cache/)
Netbeans version: 7.1.1 and also 7.0
OS version: MacOS 10.7.3
The problem lies with the Netbeans' code editor. My project compiles and it's packaged just fine. I have no problem on that. I have this annoying error messages (eg. red background) in the code editor with no reason.
A workaround I just found: Renaming the dependency project (with refactoring) and adding the new jar to my project do the trick. Still I don't know what happened.
I just had the same problem in NetBeans 7.2.1 today. I could build the project fine but got error markers in the source files and in the Projects tree listings. It seems as if the compiler when you build a project uses a different classpath from the compiler that works in the edit window.
In my case I found we had the same package and class names for different classes in different jars. I don't know if this is relevant or just a red herring.
I still had an error in one project that used these two jars. It seemed like it could only see the classes from the second jar listed in the pom.xml file (we use Maven). I commented out the second jar & rebuilt, then uncommented that second jar & rebuilt and suddenly all of my errors went away.
So I don't have a definite solution but removing and reintroducing a dependency worked for me.
How you import jar file ? You have to right click Libralies in Project Panel and click Add JAR/Folder. And select jar file which you want to import.
I think you have wrongly imported the jar file. Try out the below steps to add jar(s) to your classpath properly.
1. Select your project from the Projects explorer.
2. Right click -> Properties.
3. Select Libraries from Categories list.
4. Click on Add JAR/Folder button.
5. Add your jar(s) & click on OK to finish the process.
Now, it should resolve the reference issues
You mentioned, the editor shows errors because it cannot locate classes inside that jar. Well, are you sure you are using the right jar or right version of jar ? Eclipse is not able to locate any of the classes or only few classes ?
I wish my answer would help fixing the issue (even if too late :) )
Indeed, I have a maven project with two modules. Module1 that contains the class com.x.y.MyClass and Module2 where I'm trying to import com.x.y.MyClass.
It compiles fine, and I can run unit tests using netbeans, but the errors in the editor were embarrassing. So I add Module1 version and packaging type to the pom.xml of Module2 and that fixed my problem (I know, it's very bad to hard code a module version, but at least, I can work without worrying about the editor list of errors)
Cheers !
This is definitely too little too late, but I had this problem today with Netbeans 7.2. All jars were in place, the code was compiling from the build menu, but Netbeans was marking the files in error.
The same exact project was compiling fine with Netbeans 8.0.1.
The problem was with the "Source Root". I clicked on menu Window -> Debugging -> Sources (Alt+Shift+8) and I noticed that I had specified sources on some of the jar dependencies of the project that were no longer valid. Cleaning them up was a 2 step process:
Clean them up from the project files in nbproject dir
Clean them up from
%APPDATA%\NetBeans\7.2\config\Preferences\org\netbeans\modules\java\j2seplatform\Sources.properties
After clean up, I restarted Netbeans and everything was OK.
Hope this helps someone.
I had this issue with few jsf xhtml pages though there wasn't any error in the content of the page. So I opened each page and cut all content, saved the empty file then paste back all content and saved it. it solved the red marking error symbol for me.
I know this question is a bit old but for those who may be facing the same issue currently, hope this will help.
I faced the same challenge after moving my maven projects to a new directory. To fix the issue, I just simply
Renamed the new folder(the one containing my maven projects) just the same name as the previous folder.
Reimported the projects in Netbeans.

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:
parent project (pom-packaging)
Web project (war-packaging - my JUnit-test is in here)
Flex project
Configuration project
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("", ""));
}
}
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.
Carlos approach helped!
Eclipse - java.lang.ClassNotFoundException
Try to check the classpath of the junit run configuration:
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))
works for me.
your build classpath is correct, which is why you can compile. the classpath for your JUnit needs to be checked. go to the Run menu and choose 'open run dialog.' in there you should see a tree on the left with JUnit as an option. open that node and find and select your test. on the right pane you will see a tab for classpath. take a look to ensure that your class that the test is trying to instantiate would be found.
edit:
this seems to be an issue with maven and its behavior after a release changed the default Eclipse output folders. i have seen solutions described where
placing maven into the bootclasspath ABOVE the jre works, or
running mvn clean test does the trick or
refreshing all of your eclipse projects, causing a rebuild fixes the problem
going to your project and selecting Maven->Update Configuration solve the problem
with the first three, there were reports of the issue recurring. the last looks best to me, but if it doesnt work, please try the others.
here and here is some info
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)
The problem might be missing the class file in your build folder. One solution is clean the project and rebuild it.
There are many convoluted suggestions here.
I've encountered this problem multiple times with Maven projects after moving resources around by drag 'n' drop, or performing refactoring of class names.
If this occurs, simply copy (not move) the problem Test Case (.java) via terminal/file browser to another location, right-click -> Delete in Eclipse and choose to delete on disk when given the option, move/copy the copied file to the original file location, then select your project in Eclipse and press F5 to refresh resources.
This is quick and easy to do, and has fixed the problem permanently for me every time.
This was my solution to the problem. Of course, many things can cause it to occur. For me it was that Maven2 (not the plugin for Eclipse) was setting the eclipse profile up to use a different builder (aspectJ) but I did not have the plugin in eclipse./
http://rbtech.blogspot.com/2009/09/eclipse-galileo-javalangclassnotfoundex.html
Cheers
Ramon Buckland
Sachin's right:
Even with correct class path, the problems tab will show that some dependency or the Resource/project has error that needs to be fixed in order for maven to automatically build and create classes when you create or make a change in your test class.
"Hi,
Its very Old Jul (which year) but I had the same problem .
Actual issue found that eclipse was not able to generate class file for the java file , classpath was proper.
See the problem tab and check if your project is missing something/file. you can create a new proj and add files one by one and build them until it stops compiling and creating classes ( check the workspace/proj/bin/package/ folder for classes )
its wierd but true , ecplise was failing in compliation because 4 of 20 java files were using a single image which was missing. and as result none of the java file was compiled .
CLASSPATH is not a issue here."
We had the exact exception (using SpringSource Tools, tomcat, on Win7) and the cause was that we had refactored a filename (renamed a file) from SubDomain.java to Subdomain.java (D vs d) and somehow it collided though SpringSource was showing the new name Subdomain.java. The solution was to delete the file (via SpringSource) and create it again under the name Subdomain.java and copy-pasting its former content. Simple as that.
I had the exact same problem but I figured it out! Go to your project file and right click on it, then click Refresh or hit F5. Then try and run it. If it still doesn't work then just forget it, as I had the EXACT same problem and it just means you version of Eclipse is garbage.
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.
click on project->properties->Java build path->Source and check each src folder is still valid exist or recently removed. Correct any missing path or incorrect path and rebuild and run the test. It will fix the problem.
All I did was Properties -> Java Build Path -> Order and Export -> Enabled all unchecked boxes -> moved Junit all the way up
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
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:
Via the Run menu
Select Run Configurations
Choose the run configuration that is associated with your unit test.
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.
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.
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.
I solve that Bulit path--->libraries--->add library--->Junit check junit4
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
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.
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.
Well, you can solve this problem basically by creating a new project.
Close the project (save the code in another folder on your computer).
Create a new project (add a new final directory and do not leave the default directory selected).
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!
Please point to correct JDK from Windows > Preferences > Java > Installed JRE.
Do not point to jre, point to a proper JDK. I pointed to JDK 1.6U29 and refreshed the project.
Hereafter, the issue is gone and jUnit Tests are working fine.
Thanks,
-Tapas
I've run into a same error in Eclipse recently, i.e., the Eclipse IDE couldn't find the Unit test class no matter how I change the configurations. Learning from the previous posts here and in other web sites, I've double checked and triple checked the classpath and source info, and move up and down the source folder and libraries, in both the "Run Configuration" and the "Java Build Path" config windows, and I've also cleaned the Project and rebuilt it, but none of the tricks work for me. The specific Java project is an old ANT compiled project and have lots of jars included in Eclipse library.
Then, I changed the unit test class to add a main() method and right click it to "Run As" a Java Application instead of JUnit test, and suddenly, Eclipse seems to wake up and identified the class correctly. Afterwards, I switched it back to a Unit test application, and it is still working.
This seems to be a bug in Eclipse, I am guessing the large number of libraries (>260) may confused the JVM's ability to locate my JUnit class.
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.
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"/>
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?
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.
Changing the order of classpath artifacts in the Java Build Path resolved it for me.
Right Click on the project and go to Project Build path.
Go to, Order and Export tab and move the JRE system library to after the sources.
This should fix it.
JUnit 4.4 is not supported by the JMockit/JUnit integration. Only
versions 4.5 or newer are supported that.

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

I'm using Eclipse for Java development. All my sources compile fine and the resulting application compiles fine. However, I keep getting an "red-x" error notification in the Package Explorer.
All my sources in this source directory (too long for the snapshot) compile fine, none of the show the "red-x" error icon.
Any suggestions on how to fix the problem would be highly appreciated.
yeah, this happens sometimes for no apparent reason. You can go to the "Problems"-Tab (right next to console output) and see the error message, so maybe you can narrow it down that way.
This happens often when I use Maven, and I had always ignored it until I found this question. You need to update the project in this case (figured this out by looking in the Problems pane)
From the project context menu: Maven -> Update Project and select the available maven codebases
Alternatively you can use (Alt + F5) to bring up the same window
Try to clean the project and rebuild it.
After build. Refresh project and if still persist just right click Problems tab in eclipse and choose delete all.
It often happens if you do maven install and eclipse properties files do not get updated properly. Even though your project does not have any errors. Hopefully!
I want to start by thanking everyone that answered. But cleaning and rebuilding was not enough in my case because the problem was still there and needed fixing.
Turned out that one of my package directories had accidentally been copied so that an extra directory now existed called "Copy of dagskra" containing Java files with wrong package declarations. In addition the errors in this "new" directory don't show up with a "red-x" in the package that it exists in:
Snapshot from Package Explorer showing errorous "Copy of dagskra" directoryr http://www.freeimagehosting.net/uploads/a824304b18.png
It was the hint of reading the "Problems" tab :-) that turned me into the right direction, so I'm selecting that answer as the accepted answer because this is what I needed:
Snapshot from Problems tab http://www.freeimagehosting.net/uploads/dea26d5dd0.png
Hoping this will help others...
So upon finding that there could be a missing package in the buildpath, thus the red x against the main project, to remove this:
1) go into "Configure Buildpath" of project
2) Java Build Path -> Source Tab - you should see the red x against the missing package/file. if it no longer exists, just "remove" it.
red X begone! :)
Sometimes there are build path errors in .project, and you need to switch to Resource view to actually see the file that is causing the error.
As others have said, bad file references in the build path is often the culprit.
Usually a .jar file that has been moved/deleted. Eclipse expects to find everything referenced on the build path at the location specified, and will complain if not.
I had the same issue and below steps resolved the issue:
Delete the JRE from PROJECT> properties>java build path> libraries.
Restart the eclipse
Add the JRE again
Rebuild the project using Project>Clean and chose option to build automatically.
Please try.
Subversion is occasionally the culprit for this as well. It might not have anything to do with your environment. But, there might be a discrepancy between the current and local state of the project. In my case, doing an update, and then a commit to the subversion server provided me with the expected clean result without any flags in the project such as the X.
In my case what solved this problem was simply to Close Eclipse and opening it again...However I am still not sure why this happened or why it worked. I was having problems Cleaning my project (it said it could not Delete certain file) and this solved it :):
Try doing a rebuild. I've found that the red x's don't always disappear until a rebuild is done.
I've run into a similar problem many a time, what happens usually for me is that a java file will say it won't compile in the text editor but in the package explorer it will say it's compiling fine.
Sometimes doing a 'rebuild' or 'clean-build' doesn't work, the files don't actually get built (one has to presume that eclipse thinks the files it has are up to date) and when this happens I usually open up the java build path and just move one of my dependencies down/up the pecking order. This forces eclipse to do a rebuild of everything and it always seems to work.
If you're still having problems try copying the project and seeing if you get the same behaviour and at a last ditch attempt post a bug for eclipse, it may take a while for them to fix but at least you know that you're being heard.
To add to the previous answer, an extreme way of "cleaning" your project is to delete it (that is deleting its reference from the workspace, not deleting the actual files), and then re-import it.
Sometimes, it helps...
FindBugs also puts a red-x against files/packages to indicate static code analysis errors.
I have run through this. My case was more involved. The project was packaged fine from maven command line.
Couple of things I made.
1. One class has many imports that confused eclipse. Cleaning them fixed part of the problem
2. One case was about a Setter, pressing F3 navigating to that Setter although eclipse complained it is not there. So I simply retyped it and it worked fine (even for all other Setters)
I am still struggling with
Implicit super constructor Item() is undefined for default constructor. Must define an explicit constructor"
I also experience those misterious error-symbols on packages from time to time. A way to get rid of them that works for me is to effectively remove the JRE System Library from Java Build Path and add it back again.
My solution that finally worked was to clean all projects, close eclipse, clean all projects, close eclipse, and so on at least 5-6 times. Eventually it all settled down and everything was as expected. Weirdest thing ever!!
And no there were no errors in the Problem or console view.
Also this happened after a computer crash. The last time it happened my whole workspace was completely lost. It was still there on the computer, but when I tried to access it, it would be all blank.
For whatever reason computer crashes are really really really badly handled by eclipse.
Also, you may update the project by clicking,
Right Click on project name -> Select Maven -> Right click -> Update Project.
This helped out for me.
Thanks.
This can occur for a number of reasons. If you have changed the jdk, the Project facet will have a red X next to it while no other folders shows an error. If this is the case, modify the jdk that is shown. This happens on occasion in our JAX-WS class (HSG
I solved mine by
Close all other projects (i.e. unrelated project option)
Clean and build
My project was android, and that did it.
This happened when i downloaded fabric.io on Eclipse Mars but Restarting computer solved this problem for me.
i had same problem. I checked "Problems"-Tab and found no server for the project. I defined the server. the red-x disappered
You can go to project-> Buildpath-> Library
If there is any library that is X marked ie [cross marked] removed it and again try to build. It worked for me as well/
I encountered this problem today and found this link. I followed as mentioned by Patrick Schaefer above and opened the Update Maven project Dialog. Click on my working project and selected the checkbox "Force Update of Snapshots/Releases" and 'Ok'. All the red cross vanished.
I hope this helps anybody in a similar situation.
The question is old but I had this issue and I tried the following to no avail.
mvn update (with snapshots)
remove project and re-importing
clean build
restarting Eclipse
changing order of items in build path
In my case I've got multi module mvn projects and one of the nested projects was showing a red X icon only in the Project Explorer (package explorer and problems were totally fine) and the whole project was fine as I could run classes without any issues. So seemed like a display issue.
The only thing that worked for me was to edit the pom.xml if the offending project module and make a breaking change (add 'xxx' to a tag name) which caused 1000s of errors and then undo.
You may clean the project by clicking,
In Eclipse, Right Click on Project -> clean
This helped out for me and saved a lot of time.
Thanks.
Right click on the project with errors, then in the sub-menus select:
Maven > UpdateProject >
and then:
Select the checkbox for all the dependent projects
select force update of snapshots
click OK.
This worked for me..

Categories

Resources