You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IntelliJ中测试通过,执行mvn test/mvn clean install时失败

IntelliJ测试通过但Maven命令行执行测试失败的排查与解决

问题概述

测试代码在IntelliJ内置测试运行器中可正常通过,但执行mvn test或mvn clean install命令时测试失败。该测试用于验证CheckStatus.isSupported()方法:仅当状态为STATUS_DELIVERED时返回true。

相关代码与配置

测试代码

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(MockitoExtension.class)
public class CheckStatusTest {

    @InjectMocks
    private CheckStatus checkStatus;

    @Test
    public void testIsSupported() {
        boolean isSupported;
        for (Status status : Status.values()) {
            isSupported = checkStatus.isSupported(status, false);
            if (Status.STATUS_DELIVERED.equals(status)) {
                assertTrue(isSupported);
            } else {
                assertFalse(isSupported);
            }
        }
    }
}

Maven依赖配置

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>

环境信息

  • Maven版本:3.9.6(IntelliJ插件)
  • JDK版本:corretto-1.8.0_412(IntelliJ安装)

排查与解决方案

1. 补全JUnit Jupiter核心依赖

当前依赖仅包含mockito-junit-jupiter,缺少JUnit Jupiter的核心API和引擎依赖。IntelliJ会自动补全这些依赖,但Maven不会。需在pom.xml中添加:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <scope>test</scope>
</dependency>

2. 指定兼容的Maven Surefire插件版本

Maven默认的Surefire插件版本可能与JUnit Jupiter在JDK8环境下不兼容。需在pom.xml的build节点中指定支持JDK8的Surefire版本:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M9</version>
        </plugin>
    </plugins>
</build>

3. 优化CheckStatus实例初始化

如果CheckStatus类无依赖项,建议直接通过new关键字初始化实例,避免Mockito的@InjectMocks在Maven环境下可能出现的初始化异常:

// 替换原@InjectMocks声明
private CheckStatus checkStatus = new CheckStatus();

4. 确保枚举类正常编译

执行mvn clean compile test命令,先完成全量编译再运行测试,避免Maven clean后Status枚举类未被正确编译的问题。

内容的提问来源于stack exchange,提问作者Ayush Saxena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:50:04