无法在 Spring 引导测试 1.4 中找到 SpringBootConfiguration

Unable to find a SpringBootConfiguration in Spring Boot Test 1.4

我无法 运行 在 spring 引导 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());
    }
}

从我的角度来看,它与网站上的 post 完全一样。

@WebMvcTest 会做:

现在为什么我需要配置 "super" class

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 注释了你的测试。它 运行,检查子 classes 中的配置,没有找到,抛出异常。

你必须在测试包或子包中有配置 class 或者直接将配置 class 传递给 @ContextConfiguration@SpringBootTest 或者有 class 注释为 @SpringBootApplication.

根据@SpringBootApplication。我已经按照您在 @WebMvcTest 中提到的方式测试了控制器:如果应用程序将 class 注释为 @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.

Githubdiscussion差不多一样点。

Spring Boot Documentation