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

Gradle多模块项目如何引用其他模块Application类完成单元测试配置

配置步骤

1. 调整Gradle依赖配置

首先确保Module B的测试类路径可以引入Module A的主代码与资源,修改Module-B/build.gradle的依赖块:

dependencies {
    // 引入Module A的主代码作为测试依赖
    testImplementation project(':Module-A')
    
    // 其余原有依赖比如spring-boot-starter-test等保持不变
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

如果Module A使用了org.springframework.boot插件,默认只生成可执行的bootJar,无法被其他模块依赖,需要在Module-A/build.gradle中开启普通jar包生成:

jar {
    enabled = true
}

2. 配置测试类加载主应用上下文

在SomeControllerTest上使用@SpringBootTest注解指定Module A的启动类作为上下文入口,同时指定扫描根包覆盖两个模块的代码:

package com.example.project.other;

import com.example.project.main.Application;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import static org.junit.jupiter.api.Assertions.*;

// 指定主启动类,设置全局扫描包覆盖两个模块的业务代码
@SpringBootTest(classes = Application.class, scanBasePackages = "com.example.project")
public class SomeControllerTest {

    // 按需替换上下文中的原有Bean,实现自定义逻辑或者模拟返回
    @MockitoBean
    private YourNeedReplaceBean needReplaceBean;

    @Autowired
    private SomeController someController;

    @Test
    void testTargetMethod() {
        // 编写你的测试逻辑
    }
}

补充说明

  • 如果需要自定义额外的测试配置,可以在测试类同级添加@TestConfiguration修饰的配置类,会自动合并到主上下文中
  • 若需要使用自定义配置文件,可以通过@SpringBootTest(properties = "spring.config.location=classpath:your-test.properties")指定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:54:11