gpt4 book ai didi

java - 具有测试范围的 junit 的 Maven 构建失败

转载 作者:行者123 更新时间:2023-11-29 04:34:13 24 4
gpt4 key购买 nike

我有一个非常简单的 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

并且,在删除 <scope>test</scope> 后构建成功运行来自 junit 依赖。

为什么测试范围失败以及如何解决?

我使用的是 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

我的测试类:

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依赖在common模块下,Test类在demo模块下。

演示模块中的 pom.xml 以包含公共(public)模块依赖项:

<dependencies>

<dependency>
<groupId>myproject</groupId>
<artifactId>common</artifactId>
<version>1.0</version>
</dependency>

</dependencies>

但是,在将 MyTest 类复制到通用模块后,构建成功了。所以,似乎公共(public)模块中的 junit 依赖项没有导入到演示模块中。

最佳答案

在 Maven 中,并非所有传递依赖项(您的依赖项的依赖项)都添加到类路径中 - 这取决于范围。如果传递依赖是 testprovided 范围的,那么它们永远不会添加到类路径中。这是有道理的,因为如果您将一个库添加到您的依赖项中,您就不想依赖它的测试库。

参见 Maven 的 Introduction to the Dependency Mechanism#Dependecy Scope ,尤其是该部分底部的表格。

因此解决方案是将 junit 依赖项添加到目标模块(而不是公共(public)模块)。或者将它添加到父级(这有点老套,因为不是每个模块都可能需要这种依赖)这将有效地将它添加到所有子级。

关于java - 具有测试范围的 junit 的 Maven 构建失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42416938/

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