Spring Actuator Info端点扩展单元测试依赖注入失败问题
解决Spring Actuator Info端点扩展类的测试依赖注入问题
1. 先明确@WebMvcTest的局限
@WebMvcTest注解仅会加载Web层相关Bean,而InfoEndpoint属于Spring Boot Actuator的核心组件,不在它的自动扫描范围内,直接用该注解启动测试时,Spring容器中不会存在InfoEndpoint实例,因此会抛出依赖注入失败的错误。
2. 用@MockBean正确Mock依赖
不要使用普通的@Mock,改用@MockBean——它会将Mock对象注册到Spring应用上下文,确保你的InfoWebEndpointExtension能正常注入这个Mock实例。示例代码:
@WebMvcTest(InfoWebEndpointExtension.class) class InfoWebEndpointExtensionTest { @MockBean private InfoEndpoint infoEndpoint; @Autowired private MockMvc mockMvc; @Test void testCustomInfoResponse() throws Exception { // 配置Mock的返回值 Info mockInfo = Info.builder() .withDetail("custom_field", "test_value") .build(); when(infoEndpoint.info()).thenReturn(mockInfo); // 调用端点并验证结果 mockMvc.perform(get("/actuator/info")) .andExpect(status().isOk()) .andExpect(jsonPath("$.custom_field").value("test_value")); } }
3. SpringBootTest的正确用法
如果要做集成测试使用@SpringBootTest,记得搭配@AutoConfigureMockMvc简化测试逻辑;若需要替换特定依赖,同样用@MockBean覆盖原有Bean:
@SpringBootTest @AutoConfigureMockMvc class InfoWebEndpointExtensionIntegrationTest { @Autowired private MockMvc mockMvc; // 若扩展依赖自定义的InfoContributor,可Mock该组件 @MockBean private CustomInfoContributor customInfoContributor; @Test void testFullInfoEndpoint() throws Exception { mockMvc.perform(get("/actuator/info")) .andExpect(status().isOk()); } }
4. 检查扩展类的注入方式
确保你的InfoWebEndpointExtension采用构造函数注入InfoEndpoint,这是Spring推荐的依赖注入方式,也能让测试时的依赖管理更清晰:
@Component public class InfoWebEndpointExtension extends WebEndpointExtension<InfoEndpoint> { private final InfoEndpoint delegate; public InfoWebEndpointExtension(InfoEndpoint delegate) { super(delegate); this.delegate = delegate; } // 你的扩展逻辑代码... }
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

