我无法在 spring boot 1.4 中运行简单测试。我遵循了官方网站上的教程 testing-the-spring-mvc-slice但我没有让它工作。
每次我收到以下错误:
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
有什么想法、提示吗?
提前致谢
编辑:
这是 Controller
@Controller
public class UserManagementController {
@GetMapping(value = "/gs/users/getUsers")
public @ResponseBody String getAllUsers() {
return "test";
}
}
这是测试
@RunWith(SpringRunner.class)
@WebMvcTest(UserManagementController.class)
public class UserManagementControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void showUserView() throws Exception {
this.mvc.perform(get("/gs/users/getUsers"))
.andExpect(status().isOk())
.andDo(print());
}
}
从我的角度来看,它与网站上的这篇帖子完全一样。
@WebMvcTest
会做:
- 自动配置 Spring MVC、Jackson、Gson、消息转换器等。
- 加载相关组件(
@Controller
、@RestController
、@JsonComponent
等) - 配置模拟MVC
现在为什么我需要配置一个“ super ”类
最佳答案
The search algorithm works up from the package that contains the test until it finds a @SpringBootApplication or @SpringBootConfiguration annotated class. As long as you’ve structure your code in a sensible way your main configuration is usually found.
因此,您已经使用 @*Test 注释了您的测试。它运行,检查子类中的配置,没有找到,抛出异常。
你必须在测试类的包或子包中有一个配置,或者直接将配置类传递给 @ContextConfiguration
或 @SpringBootTest
或者用 注释类@SpringBootApplication
.
根据@SpringBootApplication
。我已经按照您在 @WebMvcTest
中提到的方式测试了 Controller :如果应用程序具有注释为 @SpringBootApplication
的类,它就会工作,如果没有,则会失败,您提到的异常。你提到的文章有备注:
In this example, we’ve omitted classes which means that the test will first attempt to load @Configuration from any inner-classes, and if that fails, it will search for your primary @SpringBootApplication class.
Github discussion大致相同点。
关于spring - 无法在 Spring Boot 测试 1.4 中找到 SpringBootConfiguration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40215606/