Unable to find a SpringBootConfiguration in Spring Boot Test 1.4

被刻印的时光 ゝ 提交于 2020-01-02 04:40:11

问题


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:


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



来源:https://stackoverflow.com/questions/40215606/unable-to-find-a-springbootconfiguration-in-spring-boot-test-1-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!