简体   繁体   English

运行 JUnit 测试时找不到类异常

[英]Class Not Found Exception when running JUnit test

I am getting this error when running JUnit test in Eclipse:在 Eclipse 中运行 JUnit 测试时出现此错误:

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.尽管我使用的是 Maven,但我尝试在类路径中添加JUnit库,并且 JUnit 库位于 POM 依赖项中。

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.我已经尝试清理项目并使用 Eclipse 的 JUnit 插件创建了一个新的 JUnit 测试用例,但仍然遇到相同的错误。

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).这似乎是因为当您使用mvn clean compile时只有源代码在编译(我使用的是 maven 3.1.0,所以我不确定它是否总是表现得像这样)。

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 .如果你运行mvn test ,测试代码也会编译,但随后它会运行测试(如果你试图通过 Eclipse 运行它们,可能不会立即需要。)解决这个问题的方法是将test-compile添加到每当您执行mvn clean时,您的 Maven 命令序列。 For example, you would run mvn clean compile test-compile .例如,您将运行mvn clean compile test-compile

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 .我的测试遇到了类似的问题,并在 Web 的某个地方发现,您必须转到项目属性中的Build Path并将Maven Dependencies移动到JRE System Library之上。 That seems to have worked for me.这似乎对我有用。

I faced the same problem and I was able to fix it using @slomek's answer but the issue resurfaced after that.我遇到了同样的问题,我能够使用@slomek 的答案修复它,但此后问题又出现了。

I finally fixed it by adding my project's output folder to the JUnit test's run configuration.我最终通过将项目的输出文件夹添加到 JUnit 测试的运行配置来修复它。 Steps are:步骤是:

  • Find your project's output folder from Project properties -> Java Build Path -> Default output folderProject properties -> Java Build Path -> Default output folder找到项目的输出文件夹
    • Usually this is <project-folder>/bin通常这是<project-folder>/bin
  • Go to Run -> Run Configurations...转到Run -> Run Configurations...
  • Click on the unit test's run configuration and click on the Classpath tab单击单元测试的运行配置,然后单击Classpath选项卡
  • Explicitly add your project's output folder under User Entries - even if the project is already included thereUser Entries下明确添加项目的输出文件夹 - 即使项目已经包含在那里
    • Click on Advanced -> Add folder to add the output folder点击Advanced -> Add folder添加输出文件夹

This issue might be due to weird project setup in Eclipse - eg source folder with nested maven projects imported as a single project/folder (at least that was how my project was setup).这个问题可能是由于 Eclipse 中奇怪的项目设置引起的——例如,带有作为单个项目/文件夹导入的嵌套 Maven 项目的源文件夹(至少我的项目是这样设置的)。

If this problem occurs in Eclipse only, executing command Project -> Clean... on selected project may help.如果此问题仅发生在 Eclipse 中,则在所选项目上执行命令 Project -> Clean... 可能会有所帮助。

After having tried everything here with no improvement, I solved my issue by just restarting Eclipse在没有任何改进的情况下尝试了这里的一切之后,我通过重新启动 Eclipse 解决了我的问题

I fixed my issue by running maven update.我通过运行 maven 更新解决了我的问题。 Right click project your project > Maven > Update Project右键单击项目你的项目> Maven > 更新项目

In my case I had a wrong maven directory structure.在我的例子中,我有一个错误的 maven 目录结构。

Which should be like:应该是这样的:

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

After I fixed that - everything worked like a charm.在我修好之后 - 一切都很顺利。

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"编辑 -> 类路径 -> “恢复默认条目”

Earlier, in this case, I always did mvn eclipse:eclipse and restarted my Eclipse and it worked.早些时候,在这种情况下,我总是执行 mvn eclipse:eclipse并重新启动我的 Eclipse 并且它起作用了。 After migrating to GIT, it stopped working for me which is somewhat weird.迁移到 GIT 后,它不再为我工作,这有点奇怪。

Basic problem here is Mr Eclipse does not find the compiled class.这里的基本问题是 Eclipse 先生没有找到已编译的类。 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:然后,我将输出文件夹设置为 Project/target/test-classes,默认情况下由mvn clean install生成而不跳过测试,并继续执行以下解决方法:

Option 1: Set classpath for each test case选项 1:为每个测试用例设置类路径

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

Option 2: Create classpath variable and include it in classpath for all the test cases选项 2:创建类路径变量并将其包含在所有测试用例的类路径中

Eclipse ->Windows ->Classpath Variables ->New->[Name: Junit_test_cases_cp | Eclipse ->Windows ->类路径变量 ->新建->[名称: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 path: ]->ok 然后去Eclipse->Run ->Run Configurations ->JUnit->select mytest ->under classpath tab ->Select User Entries->Advanced->Add classpath variables->Select Junit_test_cases_cp->ok- >应用->运行

This is the only thing currently working for me after trying all the suggestions online.在网上尝试了所有建议后,这是目前唯一对我有用的东西。

I had the similar problem with my Eclipse Helios which debugging Junits.我在调试 Junits 的 Eclipse Helios 中遇到了类似的问题。 My problem was little different as i was able to run Junits successfully but when i was getting ClassNotFoundException while debugging the same JUNITs.我的问题有点不同,因为我能够成功运行 Junits,但是当我在调试相同的 JUNIT 时遇到 ClassNotFoundException。

I have tried all sort of different solutions available in Stackoverflow.com and forums elsewhere, but nothing seem to work.我在 Stackoverflow.com 和其他地方的论坛上尝试了各种不同的解决方案,但似乎没有任何效果。 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.如果所有解决方案似乎都不起作用,只需删除在您的工作区中创建的 .metadata 文件夹。 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.希望这些有帮助。

NoClassDefFoundError really means it can't initilize the class. NoClassDefFoundError 实际上意味着它无法初始化该类。 It has nothing to do with finding the class.它与查找课程无关 I got this error when calling trim() on a null String.在空字符串上调用 trim() 时出现此错误。

JUnit won't show NullPointerException. JUnit 不会显示 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.然后您可以确定哪一行给出了错误。

In my case, changing the order of Maven Dependencies from Build Path configuration did not work for me.就我而言,从构建路径配置更改 Maven 依赖项的顺序对我不起作用。 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). • 选中使用临时 JAR 指定类路径(以避免类路径长度限制)。
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. • 在用户条目的子分支中,将Maven 依赖项移动到您的项目或测试类之上。
• Click Run button. • 单击运行按钮。

These steps worked for me.这些步骤对我有用。

  • Delete the content of local Maven repository.删除本地 Maven 存储库的内容。
  • run mvn clean install in the command line.在命令行中运行mvn clean install (cd to the pom directory). (cd 到 pom 目录)。
  • Build Project in Eclipse.在 Eclipse 中构建项目。

1- mvn eclipse:eclipse 1- mvn 日食:月食

2- project clean all projects 2-项目清理所有项目

3- restart 3-重新启动

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/值得一提的另一个答案是,如果您使用的是 eGit,并且您的类路径会因为像 Clover 这样的测试覆盖工具而更新,有时会出现清理问题,不会完全删除/path/to/git/repository/<project name>/bin/的内容/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.本质上,我使用了 Eclipse 的错误日志视图,确定了在此清理过程中导致问题的原因,导航到源目录,并手动删除了<project name>/bin目录。 Once that finished I went back to Eclipse and refreshed ( F5 ) my project and the error went away.完成后,我回到 Eclipse 并刷新 ( F5 ) 我的项目,错误消失了。

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?"也可能是由于“[ERROR] 在此环境中未提供编译器。也许您正在 JRE 而不是 JDK 上运行?”

I had the same problem with a Gradle project with a test SourceSet with two resource directories.我在 Gradle 项目中遇到了同样的问题,该项目具有带有两个资源目录的测试 SourceSet。

This snippet comes from a main-module.gradle and adds a resource dir to the test SourceSet:此代码段来自 main-module.gradle 并将资源目录添加到测试 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:这样做我有两个与项目主模块的测试 SourceSet 相关的资源目录:

../other-module/src/test/resources src/test/resources (relative to the main-module folder, automatically added by the java plugin) ../other-module/src/test/resources src/test/resources(相对于main-module文件夹,java插件自动添加)

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.结果,没有开始编译,因此 no.class 被复制到 JUnit 寻找类的 bin 目录中。 The ClassNotFoundException disappeared just renaming one of the two files. ClassNotFoundException 消失只是重命名两个文件之一。

It seems compile issue.似乎是编译问题。 Run project as Maven test, then Run as JUnit Test.将项目作为 Maven 测试运行,然后作为 JUnit 测试运行。

For project that does not use maven: This worked for me https://ihategeek.wordpress.com/2012/04/18/eclipse-junit-test-class-not-found/对于不使用 Maven 的项目:这对我有用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在 Order 的底部添加 jre 和 project src,并在 build path 中导出

Pls check if you have added junit4 as dependency.请检查您是否添加了 junit4 作为依赖项。

eg例如

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

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"对我来说,我不得不将项目 x/src/test/java/ 放在“java build path”中“order and export”的底部

在此处输入图像描述

Check if your project is opened as a Maven project and not just a regular Java project.检查您的项目是否作为 Maven 项目打开,而不仅仅是普通的 Java 项目。 Actually a no-brainer, but that is exactly the same reason why you might miss it.实际上很容易,但这正是您可能错过它的原因。

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.我通过删除外部 JUnit jar 依赖项来解决它,该依赖项是我从外部从 Internet 下载添加的。 But then I went to project->properties->build path->add library->junit->choosed the version(ex junit4)->apply.但后来我去了项目->属性->构建路径->添加库->junit->选择版本(ex junit4)->应用。

It automatically added the dependency.它自动添加了依赖项。 it solved my issue.它解决了我的问题。

Making some dummy change and saving the test class can solve the problem.进行一些虚拟更改并保存测试类可以解决问题。 It will build the.class automatically它会自动构建.class

Might be you forgotten to place the Main class and Test Case class in /src/test/java.可能是您忘记将Main 类Test Case 类放在 /src/test/java 中。 Check it Once.检查一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM