java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling

前端 未结 4 2051
遥遥无期
遥遥无期 2020-12-01 04:22

I have the following test class:

@ActiveProfiles({ \"DataTC\", \"test\" })
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {BaseTestC         


        
相关标签:
4条回答
  • 2020-12-01 04:41

    I was getting a similar error but whilst running the application normally rather than trying to run tests.

    It turns out if you're making use of a custom PermissionEvaluator then you need to declare it in a separate @Configuration class to the one with your main Spring security configuration in.

    See: How do I add method based security to a Spring Boot project?

    There is also an open Github issue: https://github.com/spring-projects/spring-boot/issues/4875

    0 讨论(0)
  • 2020-12-01 04:46

    One of your @Configuration classes is obviously annotated with @EnableWebMvc. That's how DelegatingWebMvcConfiguration ends up in your stack trace, since it is imported by @EnableWebMvc.

    So although you think you don't need a WebApplicationContext (and hence a ServletContext), you in fact do need it simply because you are loading an application context with @EnableWebMvc.

    You have two options:

    • Compose the configuration classes for your integration test so that you are not including the web-related configuration (i.e., the @Configuration class(es) annotated with @EnableWebMvc).
    • Annotate your test class with @WebAppConfiguration as suggested in other comments above.

    Regards,

    Sam (author of the Spring TestContext Framework)

    0 讨论(0)
  • 2020-12-01 04:54

    For you to instantiate the Servlet context, you would have to use the annotation.

    @WebAppConfiguration
    

    A class-level annotation that is used to declare that the ApplicationContext loaded for an integration test should be a WebApplicationContext. The mere presence of @WebAppConfiguration on a test class ensures that a WebApplicationContext will be loaded for the test, using the default value of "file:src/main/webapp" for the path to the root of the web application (i.e., the resource base path). The resource base path is used behind the scenes to create a MockServletContext which serves as the ServletContext for the test’s WebApplicationContext.

    0 讨论(0)
  • 2020-12-01 05:05

    It seems like you are missing

    @WebAppConfiguration
    

    from your test class.

    The documentation states

    The resource base path is used behind the scenes to create a MockServletContext which serves as the ServletContext for the test’s WebApplicationContext.

    Typically a Servlet container would provide the ServletContext. Since you are in a testing environment, you need a fake. @WebAppConfiguration provides that.

    0 讨论(0)
提交回复
热议问题