记录下spring boot中常用的错误
1.Spring test出现如下错误
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
代码如下
@RunWith(SpringRunner.class)
@SpringBootTest
//@SpringBootTest(classes=DemoApplication.class)
public class UserControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenQuerySuccess() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/user")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()")
.value(3));
}
}
可以在@SpringBootTest指定对应的Spring的启动类既可以解决.
本文详细解析了在使用Spring Boot进行单元测试时遇到的常见错误:无法找到@SpringBootConfiguration。通过具体代码示例,解释了如何正确配置@SpringBootTest注解以避免此问题,确保测试顺利运行。
1584

被折叠的 条评论
为什么被折叠?



