在IntelliJ中运行JUnit测试时遭遇java.lang.NoSuchMethodError异常求助
这个错误我碰到过好几次,本质是JUnit相关依赖版本不匹配——具体来说是org.junit.platform.commons.util.Preconditions.notNull方法找不到,说明项目里的JUnit Platform模块版本和IntelliJ运行测试时依赖的版本冲突了,或者你混用了不同版本的JUnit 5组件。下面是一步步的解决办法:
统一所有JUnit 5组件的版本
这是最常见的原因:比如你用了JUnit Jupiter API 5.7.0,但引擎(Engine)却用了5.9.0,或者间接引入了旧版本的JUnit Platform Commons。一定要保证所有JUnit 5相关依赖的版本完全一致。
举个Maven的配置例子(用最新稳定版就行):<properties> <junit-jupiter.version>5.9.2</junit-jupiter.version> </properties> <dependencies> <!-- 编写测试用的API --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit-jupiter.version}</version> <scope>test</scope> </dependency> <!-- 运行测试的引擎 --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit-jupiter.version}</version> <scope>test</scope> </dependency> </dependencies>Gradle的话这么写:
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.2'检查IntelliJ的测试配置
打开File > Settings > Build, Execution, Deployment > Build Tools,选你用的Maven或Gradle,确保IDE使用的是项目本地的依赖,而不是自带的旧版本。另外,在测试的运行配置里(Run/Debug Configurations),确认测试Runner选的是JUnit 5,别选错成JUnit 4了。清理缓存并重新构建
旧的依赖缓存经常搞事情,按顺序做这几步:- 点击
Build > Clean Project清空编译产物 - 再点
Build > Rebuild Project重新编译 - 用命令行刷新依赖:Maven执行
mvn clean install -U,Gradle执行./gradlew clean build --refresh-dependencies
- 点击
排除冲突的间接依赖
如果项目里其他依赖偷偷引入了旧版本的JUnit Platform,就得把它排除掉。先用依赖树命令找出冲突:- Maven:
mvn dependency:tree - Gradle:
./gradlew dependencies
找到带有旧版本org.junit.platform:junit-platform-commons的依赖,然后在pom.xml或build.gradle里排除它,比如Maven的例子:
<dependency> <groupId>你的依赖组ID</groupId> <artifactId>你的依赖 artifact ID</artifactId> <version>版本号</version> <exclusions> <exclusion> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-commons</artifactId> </exclusion> </exclusions> </dependency>- Maven:
另外,如果你的IntelliJ版本比较老,可能和新版本JUnit 5不兼容,这种情况要么升级IDE到最新稳定版,要么把JUnit 5的版本降到和IDE兼容的(比如IntelliJ 2021.3建议用JUnit 5.8.x及以下)。
内容的提问来源于stack exchange,提问作者Joshua Davies

