问题描述
在 Eclipse 中运行 JUnit 测试时出现此错误:
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)
尽管我使用的是 maven,但我已经尝试在类路径中添加 JUnit
库,并且 JUnit 库位于 POM 依赖项中.
I've tried adding JUnit
library in the classpath although I'm using maven, and the JUnit library is in the POM dependency.
我已经尝试清理项目并使用 Eclipse 的 JUnit 插件创建了一个新的 JUnit 测试用例,但仍然遇到相同的错误.
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.
推荐答案
出现这种情况是因为使用 mvn clean compile
时只有源代码在编译(我使用的是 maven 3.1.0所以我不确定它是否总是这样).
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 test
,测试代码也会编译,但随后它会运行测试(如果您尝试通过 Eclipse 运行它们,这可能不是立即可取的.)解决这个问题的方法是在执行 mvn clean
时将 test-compile
添加到您的 Maven 命令序列中.例如,您将运行 mvn clean compile test-compile
.
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
.
这篇关于运行JUnit测试时找不到类异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!