Java 在Maven中运行JUnit测试时发生ClassNotFoundException
我目前正试图为一个Maven项目设置自动测试,但遇到了一个问题。使用Java 在Maven中运行JUnit测试时发生ClassNotFoundException,java,maven,junit,Java,Maven,Junit,我目前正试图为一个Maven项目设置自动测试,但遇到了一个问题。使用mvn test运行测试时,我得到以下结果: ------------------------------------------------------------------------------- Test set: no.digipat.patornat.servlets.ServletTests -------------------------------------------------------------
mvn test
运行测试时,我得到以下结果:
-------------------------------------------------------------------------------
Test set: no.digipat.patornat.servlets.ServletTests
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.398 s <<< FAILURE! - in no.digipat.patornat.servlets.ServletTests
no.digipat.patornat.servlets.ServletTests Time elapsed: 0.368 s <<< ERROR!
java.lang.NoClassDefFoundError: com/mongodb/OperationExecutor
Caused by: java.lang.ClassNotFoundException: com.mongodb.OperationExecutor
MyTest.java:
package no.digipat.patornat.servlets;
import static org.junit.Assert.*;
import org.junit.Test;
public class MyTest {
@Test
public void test() {
fail("Not yet implemented");
}
}
有没有办法解决这个问题?我试着运行
mvn clean
(这之前帮助我解决了一个类似的问题),但没有成功。我想您需要pom.xml中的maven编译器插件
<build>
<!-- put here the path of your test source directory -->
<testSourceDirectory>src/test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
...
src/测试
org.apache.maven.plugins
maven编译器插件
${maven.compiler.source}
${maven.compiler.target}
...
问题似乎在于Fongo和mongo java驱动程序的最新版本不兼容。当我将Fongo和/或Mongo Java驱动程序的依赖项更改为旧版本时(我分别专门尝试了版本2.1.0和3.6.3),错误就会消失。然而,由于这个解决方案似乎相当脆弱和不灵活,最好的办法可能是改用Fongo的替代方案。据报道,这可能是一个不错的选择。一个可能更健壮的替代方法,也是我最终可能使用的方法,是使用一个“真实的”测试数据库。提供了有关几种方法的信息。测试范围需要它:org.mongodb mongo java driver 3.4.1 test@Cayman,这将缩小范围,因为在运行测试时,具有“compile”范围的依赖项是可用的。除此之外,它不是一个真正的选项,因为我需要Mongo驱动程序进行的不仅仅是测试。
package no.digipat.patornat.servlets;
import static org.junit.Assert.*;
import org.junit.Test;
public class MyTest {
@Test
public void test() {
fail("Not yet implemented");
}
}
<build>
<!-- put here the path of your test source directory -->
<testSourceDirectory>src/test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
...