在junit多模块项目中统一版本的核心做法是在父pom的

如何配置父POM以管理JUnit依赖
通过在父POM中引入

<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>junit-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<junit.version>5.10.0</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
</plugin>
</plugins>
</build>
</project>
上述代码展示了父POM的结构。关键部分在于
子模块如何继承并简化依赖声明
子模块通过继承父POM,自动获得依赖管理的约束。在子模块的POM中,只需声明需要的JUnit依赖坐标,省略版本号即可。这种机制利用了Maven的依赖调解原则,优先使用父POM中定义的版本。

<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>junit-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>junit-child-module</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
子模块代码中,
当子模块显式指定不同版本时会发生什么
如果在子模块中显式为JUnit依赖指定了与父POM不同的版本,Maven的依赖调解机制将介入。通常情况下,最先在依赖树中出现的版本会被选中,但这可能导致不可预测的结果。更常见的情况是,如果子模块直接覆盖了父POM中的版本声明,可能会导致该子模块使用的版本与其他子模块不一致,从而引发测试失败。
为了验证这一点,假设子模块尝试覆盖版本:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
在这种情况下,该子模块将使用5.9.0版本,而其他未覆盖的子模块仍使用5.10.0。这种版本分裂会导致类路径中存在多个版本的JUnit库,可能引起NoSuchMethodError或ClassNotFoundException等运行时错误。因此,最佳实践是禁止在子模块中显式指定由父POM管理的依赖版本,保持版本的一致性。

















