Unable to find a SpringBootConfiguration in Spring

2019-04-29 15:49发布

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.

every time i get the following error:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

any ideas, hints?

Thanks in advance

Edit:

this is the controller

@Controller
public class UserManagementController {

@GetMapping(value = "/gs/users/getUsers")
    public @ResponseBody String getAllUsers() {
        return "test";
    }
}

this is the 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.

the @WebMvcTest will do:

  • Auto-configure Spring MVC, Jackson, Gson, Message converters etc.
  • Load relevant components (@Controller, @RestController, @JsonComponent etc)
  • Configure MockMVC

now why i need to configure a "super" class

1条回答
做个烂人
2楼-- · 2019-04-29 16:08

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.

So you have annotated your test with @*Test. It run, checked for configuration in subclasses, haven't found any, thrown an exception.

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.

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:

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 about the same point.

Spring Boot Documentation

查看更多
登录 后发表回答