无法在Spring Boot Test 1.4中找到SpringBootConfiguration

前端之家收集整理的这篇文章主要介绍了无法在Spring Boot Test 1.4中找到SpringBootConfiguration前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我无法在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
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,@ RestartController,@ JsonComponent等)
>配置MockMVC

现在为什么我需要配置一个“超级”类

最佳答案

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提到的方式测试了控制器:如果应用程序将类注释为@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 Boot Documentation

原文链接:https://www.f2er.com/springboot/431769.html

猜你在找的Springboot相关文章