gpt4 book ai didi

java - 依赖项的测试资源不在类路径中?

转载 作者:IT老高 更新时间:2023-10-28 13:55:03 26 4
gpt4 key购买 nike

我有一个使用 Maven 设置的多模块 Spring 项目:

my-root (pom)
- my-logic
- my-webapp (depending on my-logic)
- my-consoleapp (depending on my-logic)

我的测试类继承自 AbstractTransactionalJUnit4SpringContextTests并使用 @ContextCofiguration用于设置 ApplicationContext .

例如Spring Controller 的测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:applicationContext-logic-test.xml",
"classpath:applicationContext-web-test.xml"})
public class ControllerTest extends AbstractTransactionalJUnit4SpringContextTests {

@Autowired
private ApplicationContext applicationContext;
...
}

如您所见,每个模块都有一个配置 XML。我有单独的配置用于测试,驻留在每个模块的测试/资源中(另外还有后缀“-test”)。这一切正常(类编译、运行并且 JUnit 测试成功)如果我在 Eclipse 中运行 JUnit 测试。

现在我的问题是:使用 Maven 运行测试将不起作用!(例如,在 my-root 上使用“运行方式”>“Maven 安装”(我使用 m2eclipse))。具体来说,会抛出如下异常:

java.io.FileNotFoundException: class path resource [applicationContext-logic-test.xml] cannot be opened because it does not exist`

似乎 Maven 没有添加来自 my-logic/src/test/resources 的文件到运行 my-webapp 的单元测试时设置的类路径.

我该如何解决这个问题?

最佳答案

It seems that Maven does not add the files from my-logic/src/test/resources to the classpath that is set up when running the unit tests of my-webapp.

不,确实没有。首先,Maven 使用总是通过本地存储库解析的二进制依赖项。其次,二进制依赖项不包括测试内容。

但你可以做的是:

  1. 配置 my-logic 模块以使用 jar:test-jar 创建测试 JAR
  2. my-webapp 模块配置为依赖此测试 JAR(使用 test 范围)。

对于#1,您必须在 my-logic 的 pom.xml 中配置 Maven Jar 插件:

<project>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

Maven 会在 package 期间创建一个包含 target/test-classes 内容的 JAR 并安装/部署它。

对于#2,在 my-webapp 的 pom.xml 中声明对测试 JAR 的依赖:

<project>
...
<dependencies>
<dependency>
<groupId>com.myco.app</groupId>
<artifactId>foo</artifactId>
<version>1.0-SNAPSHOT</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
...
</project>

应该可以的。

关于java - 依赖项的测试资源不在类路径中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3571149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com