我知道这个问题已经被问过很多次了,但我读过的方法对我来说不起作用。我试过this但还是不行。
我有一个子项目(A),它依赖于另一个子项目(B)。
两个子项目都包含在父目录中,并且在各自的子目录中具有父 pom.xml(将 A 和 B 声明为模块)。
编译和安装项目可以使用 maven-assemble-plugin 正常工作,但是当我尝试测试 A 时,它无法识别 B 中的类。 我尝试先安装它,然后进行测试,但它仍然找不到类。我错过了什么?
错误:
[ERROR] Failed to execute goal
org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile
(default-testCompile) on project (A)
[ERROR] TestService.java:[8,17] cannot find symbol
[ERROR] symbol: class **Model** (the class I'm referencing in B)
[ERROR] location: class **TestService**
(test in A that tests the class in ../service/src/main/java/Service.java)
编辑:
/项目
--/service(这取决于型号;这也是我想测试的)
---/src
----/主要
---/java
------/Service.java
----/测试
---/java
------/TestService.java
--/模型(独立)
---/src
----/主要
---/java
------/Model.java
--/entry(这取决于服务;整个项目的入口点)
--pom.xml(父pom)
这三个项目都有自己的 pom.xml 。
/model/pom.xml 不包含任何依赖项和插件
这是父级: 父/pom.xml
...
<modules>
<module>entry</module>
<module>service</module>
<module>model</module>
</modules>
这里是条目:
/service/pom.xml
...
<parent>
<groupId>com.some.project</groupId>
<artifactId>project</artifactId>
<version>xx</version>
</parent>
<artifactId>entry</artifactId>
<packaging>jar</packaging>
<version>xx</version>
<name>entry</name>
<build>
...
<!--assembly plugin is declared here-->
</build>
<dependencies>
<dependency>
<groupId>com.some.project</groupId>
<artifactId>service</artifactId>
<version>xx</version>
</dependency>
</dependencies>
这里的服务:
/service/pom.xml
...
<parent>
<groupId>com.some.project</groupId>
<artifactId>project</artifactId>
<version>xx</version>
</parent>
<artifactId>service</artifactId>
<packaging>jar</packaging>
<version>xx</version>
<name>service</name>
<dependencies>
<dependency>
<groupId>com.some.project</groupId>
<artifactId>model</artifactId>
<version>xx</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
最佳答案
Maven组装插件通常在你想要打包已经编译好的源代码时使用,所以这里不相关。
如果你有两个项目,A 和 B,并且 B 必须依赖于 A,你必须在 B 的 pom.xml 中定义一个依赖项(简单的东西):
<dependency>
<groupId>YOUR_GROUP_ID</groupId>
<artifactId>A</artifactId>
<version>YOUR_VERSION</version>
</dependency>
这将指示 maven 在构建期间设置类路径。
现在,根据 A 和 B 的 Artifact 类型,maven 可以决定编译后的一些步骤,例如,如果 B 是 WAR,则由于这种依赖关系,A 将包含在 B 的 WEB-INF/lib 文件夹中。
但一般来说,如果 A 和 B 是 jar,maven 不会仅将这些信息用于编译/测试,而不用于打包。
现在,maven 对于不同的阶段有不同的类路径:具体来说,一种用于编译,一种用于单元测试。
因此,如果您想指定仅测试需要该依赖项,但不应将其视为“编译”依赖项,请定义范围:
<dependency>
<groupId>YOUR_GROUP_ID</groupId>
<artifactId>A</artifactId>
<version>YOUR_VERSION</version>
<scope>test</scope>
</dependency>
如果您没有指定任何范围,maven 将得出结论,编译和测试都需要依赖项,甚至可能是打包所需的依赖项,正如我之前所解释的。
关于java - Maven - 如何对依赖于另一个项目的项目进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510076/