[英]Maven build failing for junit with test scope
我有一个非常简单的junit测试类,它使用Eclipse JUnit启动程序成功运行。
下面是JUnit的pom依赖项。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
...
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
</plugin>
</plugins>
</build>
</project>
但是,在运行maven构建时,我收到以下错误消息:
MyTest.java:[3,24] package org.junit does not exist
并且,从junit依赖项中删除<scope>test</scope>
后,构建成功运行。
为什么它失败了测试范围以及如何修复它?
我使用的是Java 8和Maven 3.3.9版本。
编辑 - 添加了最小,完整和可验证的代码
由于我无法共享实际代码,因此我创建了一个演示测试类,并在下面得到了相同的错误。
/MyProject/demo/src/test/java/com/MyTest.java:[3,24] package org.junit does not exist
/MyProject/demo/src/test/java/com/MyTest.java:[3,1] static import only from classes and interfaces
/MyProject/demo/src/test/java/com/MyTest.java:[5,17] package org.junit does not exist
MyTest类:
package com;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MyTest {
@Test
public void demo() throws Exception {
int expected = 10;
int actual = 10;
assertEquals(expected, actual);
}
}
此外,它是一个多模块项目。 JUnit依赖项在公共模块下,Test类在demo模块下。
演示模块中的pom.xml包含常见的模块依赖项:
<dependencies>
<dependency>
<groupId>myproject</groupId>
<artifactId>common</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
但是,在将MyTest类复制到公共模块后,构建成功。 因此,看起来普通模块中的junit依赖项不会导入到演示模块。
在Maven中,并非所有传递依赖项(依赖项的依赖项)都被添加到类路径中 - 它取决于范围。 如果传递依赖项是test
或provided
作用域,则它们永远不会添加到类路径中。 这是有道理的,因为如果向依赖项添加lib,则不希望依赖于其测试库。
请参阅Maven的依赖机制简介#Dependecy Scope ,尤其是本节底部的表格。
因此,解决方案是将junit依赖项添加到目标模块(而不是您的公共模块)。 或者将它添加到父级(这有点hacky,因为不是每个模块都可能需要这种依赖),这将有效地将它添加到所有子级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.