SpringBoot3+JUnit5测试时无法读取application-test.yml配置的问题
解决SpringBoot3+JUnit5测试Controller时配置类注入空指针问题
问题根源
你的测试出现空指针是因为两个核心问题:
- Mockito与Spring上下文不兼容:用
@InjectMocks创建Controller实例,再通过MockMvcBuilders.standaloneSetup启动独立Controller,这种方式不会触发Spring的依赖注入机制,导致Controller里的echoProperties字段始终为null。 - 测试上下文配置不全:仅用
@ContextConfiguration和@EnableConfigurationProperties无法完整加载Spring Boot的配置绑定逻辑,也不会自动将配置类注入到Controller中。
解决方案(两种可选)
方案一:用@WebMvcTest做Controller切片测试(推荐,轻量高效)
这是Spring Boot专门为Controller测试设计的切片注解,只会加载Controller相关的Bean和配置,启动速度快:
@WebMvcTest(EchoPlusPlusController.class) @EnableConfigurationProperties(EchoProperties.class) class EchoPlusPlusControllerTest { @Autowired private MockMvc mockMvc; @Autowired private EchoProperties echoProperties; @Test void testEchoMessageSuccess() throws Exception { MockHttpServletResponse response = mockMvc .perform(MockMvcRequestBuilders.get("/api/echo-echoplusplus/echomessage") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn() .getResponse(); String responseString = response.getContentAsString(); EchoPlusPlusResponse actualResponse = new ObjectMapper().readValue(responseString, EchoPlusPlusResponse.class); System.out.println("greeting: " + echoProperties.getMessage()); assertNotNull(response); // 注意:原断言里的"hello world!"和配置文件的"hello world"不一致,需修正 assertEquals("hello world", actualResponse.getEchoPlusPlusRes().getMessage()); } }
关键说明:
@WebMvcTest自动配置MockMvc,无需手动初始化;@EnableConfigurationProperties确保EchoProperties被加载并绑定application-test.yml中的配置;- Spring会自动将配置类注入到Controller中,彻底解决空指针问题。
方案二:用@SpringBootTest加载完整上下文(适合需要完整环境的测试)
如果你的测试需要依赖更多Spring组件(比如Service、Repository),可以用完整上下文测试:
@SpringBootTest @AutoConfigureMockMvc class EchoPlusPlusControllerTest { @Autowired private MockMvc mockMvc; @Autowired private EchoProperties echoProperties; @Test void testEchoMessageSuccess() throws Exception { MockHttpServletResponse response = mockMvc .perform(MockMvcRequestBuilders.get("/api/echo-echoplusplus/echomessage") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn() .getResponse(); String responseString = response.getContentAsString(); EchoPlusPlusResponse actualResponse = new ObjectMapper().readValue(responseString, EchoPlusPlusResponse.class); System.out.println("greeting: " + echoProperties.getMessage()); assertNotNull(response); assertEquals("hello world", actualResponse.getEchoPlusPlusRes().getMessage()); } }
关键说明:
@SpringBootTest加载完整的Spring Boot上下文;@AutoConfigureMockMvc自动配置MockMvc;- 配置类会被正常加载并注入到Controller中。
额外注意点
- 原测试中的断言
assertEquals("hello world!", ...)和application-test.yml里的"hello world"不一致,会导致断言失败,必须修正匹配; - 确保
src/test/resources/application-test.yml的配置格式正确,YAML对缩进敏感,避免因缩进错误导致配置读取失败。
内容的提问来源于stack exchange,提问作者tpdovu
相关产品推荐
相关产品推荐

