【发布时间】:2014-12-04 16:56:25
【问题描述】:
当我在 IntelliJ 中运行测试时,我在访问资源文件时遇到问题。当我从 Maven 运行相同的测试时,一切都按预期工作。
maven3 项目有 2 个模块:database-module 和 webapp-module。 webapp-module 依赖于 database-module。
文件:
database-module/src/main/resources/dataSource.xml
database-module/src/test/resources/dataSource.xml
database-module/src/test/java/org/example/DataSourceTest.java
webapp-module/src/test/java/org/example/HomeControllerTest.java
数据库模块中有一个测试类DataSourceTest。测试使用类路径中的 dataSource.xml。
DataSourceTest.java 包含:
@Value("classpath:dataSource.xml")
private Resource myDataSource;
注解@Value 是org.springframework.beans.factory.annotation.Value。
当我运行测试时,变量 myDataSource 包含来自 src/test/resources 的数据。它适用于 maven 和 IntelliJ。
我在 webapp-module 中有另一个测试 HomeControllerTest。该测试还以与 DataSourceTest 相同的方式使用 dataSource.xml。但是从 maven 和 IntelliJ 运行测试是有区别的:
如果我从 maven 运行 HomeControllerTest,它会按预期工作:它使用 database-module/src/main/resources/dataSource.xml。 如果我从 IntelliJ 运行 HomeControllerTest,它会使用 database-module/src/test/resources/dataSource.xml。
dataSource.xml 文件只存在于 database-module 中,webapp-module 中没有 dataSource.xml。
我在运行 HomeControllerTest 时打印出 IntelliJ 中的类路径,我很惊讶数据库模块中的测试类存在,即使 HomeControllerTest 是 webapp-module 的一部分。
类路径(从 IntelliJ 运行测试时):
C:/myproject/database-module/test-classes
C:/myproject/database-module/classes
C:/myproject/webapp-module/test-classes
C:/myproject/webapp-module/classes
测试使用 JUnit4。
当我从 webapp-module 调用测试时,为什么类路径上有 database-module/test-classes? 如何更改 IntelliJ 行为以匹配构建类路径的 maven 方式?
【问题讨论】:
-
你的 webapp 模块对数据库模块有依赖关系吗?
-
是的,我愿意。当我执行“mvn clean install”时,首先构建数据库模块,然后是 webapp 模块。 HomeControllerTest 使用数据库模块中的 dataSource.xml,因此依赖关系明显存在。但是,当我使用 IntelliJ 时,HomeControllerTest 会选择错误的 dataSource.xml(即 database-module/src/test/resources/dataSource.xml 而不是 database-module/src/main/resources/dataSource.xml)。
-
你确定 webapp-module 对 database-module test-jar 没有依赖关系吗? Intellij Run/Debug Configuration -> Your test -> Use classpath of module 中的值是什么
-
我确信 webapp-module 对 database-module 测试 jar 没有依赖关系,因为我在使用 maven 构建项目时得到了预期的结果。当我选择“测试类型”:“全部在包中”和“搜索测试”:“在整个项目中”时,“使用模块的类路径”设置被禁用。问题原来是 IntelliJ 问题。
标签: java maven intellij-idea junit classpath