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
相关产品推荐
相关产品推荐

