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

如何在Spring Boot 1.2.5.RELEASE中使用@MockBean及替代方案

1. Spring Boot 1.2.5.RELEASE 版本无法使用@MockBean

@MockBean是Spring Boot 1.4.0版本才正式引入的测试工具注解,1.2.5版本原生并不支持。你单独升级spring-boot-starter-test到2.x版本会出现依赖不兼容问题,你遇到的java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotationUtils.getRepeatableAnnotations报错,就是高版本测试依赖调用了低版本Spring Core不存在的方法导致的,在不修改Spring Boot父版本的前提下,这个依赖冲突无法解决,因此1.2.5版本不能使用@MockBean。


2. 可行的替代方案

方案1:手动配置测试用@Primary Mock Bean(适用集成测试场景)

如果你需要启动完整Spring上下文做集成测试,可以在测试类的内部配置类中手动定义Mock Bean,并标注更高优先级的@Primary,覆盖业务代码中的原@Primary Bean:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = 你的启动类.class)
@ActiveProfiles("test")
public class 你的测试类 {

    @Configuration
    static class TestMockConfig {
        @Bean
        @Primary
        public 你要Mock的类名 mockTargetBean() {
            return Mockito.mock(你要Mock的类名.class);
        }
    }

    @Autowired
    private 你要Mock的类名 mockBean;

    @Autowired
    private 待测试的业务类 service;

    @Test
    public void 测试方法() {
        // 自定义Mock返回逻辑
        Mockito.when(mockBean.目标方法()).thenReturn("自定义返回值");
        // 执行测试&断言
        Assert.assertEquals("预期结果", service.业务方法());
    }
}

Spring加载Bean时会优先使用测试配置类中定义的@Primary Bean,因此会自动将Mock对象注入到所有依赖位置,和@MockBean的效果完全一致。

方案2:纯单元测试方案(无需启动Spring上下文)

如果不需要依赖Spring上下文的其他能力,直接用Mockito原生注解做纯单元测试,完全不需要处理Spring的@Primary逻辑,执行速度更快:

@RunWith(MockitoJUnitRunner.class)
public class 你的测试类 {
    @Mock
    private 你要Mock的类名 mockBean;

    @InjectMocks
    private 待测试的业务类 service;

    @Test
    public void 测试方法() {
        Mockito.when(mockBean.目标方法()).thenReturn("自定义返回值");
        Assert.assertEquals("预期结果", service.业务方法());
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:39:04