How to run tests using a custom WebApplicationInitializer?

后端 未结 2 1274
感情败类
感情败类 2020-12-31 14:11
class MyWebAppInitializer extends WebApplicationInitializer {
  def onStartup(servletContext: ServletContext): Unit = {
      ...
  }
}

@RunWith(classOf[SpringJUnit         


        
相关标签:
2条回答
  • 2020-12-31 14:52

    The answer is "Sorry,you can't". You could refer to this: Spring FrameworkSPR-10199 Add capability to use WebApplicationInitializer for testing Spring web applications

    Just as Sam Brannen said:

    Although Spring does provide mocks for the Servlet API, Spring does not mock a Servlet container and currently has no intention to. Spring has always focused on out of container integration testing. Fully mocking a container is therefore beyond the scope of Spring's testing support. Please see comments from Rossen and me above for further details.

    0 讨论(0)
  • 2020-12-31 14:53

    In your context configuration I don't see that you have a context loader listed. The AnnotationConfigWebContextLoader will locate instances of WebApplicationInitializer on your classpath, by adding this and removing the intializers (which, as you have noted, are for ApplicationContextInitializers and not WebApplicationInitializers) then you should be all set.

    @RunWith(classOf[SpringJUnit4ClassRunner])
    @WebAppConfiguration
    @ContextConfiguration(classes = {ConfigClass.class, AnotherConfigClass.class}, loader=AnnotationConfigWebContextLoader.class))
    class MyTest {
    ...
    

    Here is a working example

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(classes={WebConfiguration.class, SecurityConfig.class}, loader=AnnotationConfigWebContextLoader.class)
    @ActiveProfiles("dev")
    public class AppTests {
        private MockMvc mockMvc;
    
        @Autowired
        protected WebApplicationContext webApplicationContext;
    
        @Before
        public void setup() {
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        }
    
        @Test
        public void simple() throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.get("/"))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.view().name("index"));
        }
    }
    
    0 讨论(0)
提交回复
热议问题