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

如何在@SpringBootTest测试类中使用TestConfig内的@MockBean实例

Spring Boot集成测试中为MockBean配置不同测试用例行为

你的TestConfig已经通过@MockBean把RandomExecutor声明为模拟Bean并加入Spring测试上下文了,接下来只需要在测试类中注入这个Mock实例,然后为每个测试用例单独定义行为即可:

步骤1:在测试类中注入MockBean

在ServiceIntegTest里通过@Autowired注入配置好的RandomExecutor模拟实例:

@SpringBootTest(classes = TestConfig.class)
class ServiceIntegTest {

    @Autowired
    private RandomExecutor randomExecutor;

    // 测试用例写在这里
}

步骤2:为每个测试用例自定义行为

利用Mockito的API(比如when()、doAnswer()),在每个测试方法里单独设置RandomExecutor的方法行为,Spring Boot会自动在每个测试方法执行前重置Mock状态,确保用例间互不干扰:

@SpringBootTest(classes = TestConfig.class)
class ServiceIntegTest {

    @Autowired
    private RandomExecutor randomExecutor;

    // 测试用例1:模拟方法返回指定结果
    @Test
    void testCase1() {
        // 定义该用例下execute方法的行为
        Mockito.when(randomExecutor.execute()).thenReturn("用例1专属结果");
        
        // 执行你的业务逻辑测试,比如调用依赖RandomExecutor的服务
        // ...
    }

    // 测试用例2:模拟方法抛出异常
    @Test
    void testCase2() {
        // 定义该用例下execute方法的行为
        Mockito.when(randomExecutor.execute()).thenThrow(new RuntimeException("用例2触发异常"));
        
        // 执行对应的业务逻辑测试,验证异常处理逻辑
        // ...
    }
}

TestConfig保持原配置即可:

class TestConfig {

    @MockBean
    RandomExecutor randomExecutor;
}

关键说明

  • @MockBean会替换Spring上下文中原有的RandomExecutor Bean(如果存在),确保测试时用的是模拟实例
  • 每个测试方法执行前,Spring会自动重置Mock的状态,所以不用手动清除之前的配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:06:20