无法在 Spring Boot Test 1.4 中找到 SpringBootConfiguration [英] Unable to find a SpringBootConfiguration in Spring Boot Test 1.4
问题描述
我无法在 spring boot 1.4 中运行简单的测试.我按照官方网站的教程 testing-the-spring-mvc-slice 但我没有让它工作.
I'm not able to run a simple test in spring boot 1.4. I followed the tutorial from the official site testing-the-spring-mvc-slice but I didn't get it to work.
每次我收到以下错误:
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
任何想法,提示?
提前致谢
这是控制器
@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());
}
}
在我看来,它与网站上的这篇文章完全一样.
From my point of view it's exactly the same like this post from the site.
@WebMvcTest
会做:
- 自动配置 Spring MVC、Jackson、Gson、消息转换器等
- 加载相关组件(
@Controller
、@RestController
、@JsonComponent
等) - 配置 MockMVC
现在为什么我需要配置一个超级"类
now why i need to configure a "super" class
推荐答案
搜索算法从包含测试的包开始直到找到 @SpringBootApplication 或 @SpringBootConfiguration注释类.只要您以合理的方式构建代码通常找到您的主要配置的方式.
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 注释了你的测试.它运行,检查子类中的配置,没有找到,抛出异常.
So you have annotated your test with @*Test. It run, checked for configuration in subclasses, haven't found any, thrown an exception.
你必须在测试类的包或子包中有一个配置或直接将配置类传递给@ContextConfiguration
或@SpringBootTest
或用注释类@SpringBootApplication
.
You have to have a config in a package or subpackage of test class or directly pass config class to @ContextConfiguration
or @SpringBootTest
or have class annotated with @SpringBootApplication
.
根据@SpringBootApplication
.我已经按照您在 @WebMvcTest
中提到的方式测试了控制器:如果应用程序的类注释为 @SpringBootApplication
,它就可以工作,如果没有,则失败并出现您提到的异常.你提到的那篇文章有备注:
According to @SpringBootApplication
. I have tested controller in way you have mentioned with @WebMvcTest
: it works if application has class annotated as @SpringBootApplication
and fails with exception you've mentioned if not. There is remark it the article you mentioned:
在这个例子中,我们省略了类,这意味着测试将首先尝试从任何内部类加载 @Configuration,如果失败,它将搜索您的主要 @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 讨论关于同一点.
Github discussion about the same point.
这篇关于无法在 Spring Boot Test 1.4 中找到 SpringBootConfiguration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!