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

如何Mock服务返回Null以触发Controller的else代码块?

如何Mock服务返回Null触发Controller的404分支

你可以通过Mockito框架模拟服务的行为,强制它在传入指定ID时返回null,从而触发Controller的404分支。具体操作如下:

  • 在测试类中注入Mock的服务实例:在你的Controller测试类中,使用@MockBean注解替换真实的myService实例,确保测试时使用Mock对象而非真实服务逻辑:

    @Autowired
    private MockMvc mockMvc;
    
    @MockBean
    private MyService myService; // 替换为你实际的服务类名称
    
  • 指定Mock方法的返回行为:在测试方法内,通过Mockito的when()方法定义规则:当调用myService.getPersonById("123")时,返回null:

    @Test
    public void testGetPersonByIdReturns404() throws Exception {
        // 配置Mock服务,传入id="123"时返回null
        when(myService.getPersonById("123")).thenReturn(null);
    
        // 执行请求并验证返回404状态码
        mockMvc.perform(get("/issuers/{id}", "123"))
                .andExpect(status().is(404));
    }
    

这样,当Controller调用myService.getPersonById("123")时,Mock服务会返回null,进而触发else代码块,返回404状态码。只要保证when()中的方法签名和Controller中调用的完全一致,就能精准控制服务的返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 13:22:36