\"Class not found\" when run/debug JUnit tests

在使用maven,eclipse,junit的项目中,打包后再进行单元测试常常会报找不到类

Class not found com.xxx.service.XxxServiceTest

java.lang.ClassNotFoundException: com.xxx.service.XxxServiceTest

at java.net.URLClassLoader$1.run(Unknown Source)

at java.security.AccessController.doPrivileged(Native Method)

at java.net.URLClassLoader.findClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

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)

解决方法是Project-clean。

原因是:

如果没使用maven,eclipse默认会去bin目录找class文件,如果使用了maven,则会去target\test-classes目录下去找class文件。刚好我的打包脚本中包含了mvn clean命令,将target\test-classes目录下的文件清空了,在target\test-classes目录还没有对应的class文件,所以会抛ClassNotFoundException!Project-clean操作让eclipse重新编译,刚好可以解决这个问题。

相关推荐