Using Spring Boot

 

Testing the Spring Context




Starting with Spring 3.1, we get first-class testing support for @Configuration classes:


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {WebConfig.class, PersistenceConfig.class},
loader = AnnotationConfigContextLoader.class)
public class SpringTest {


@Test
public void whenSpringContextIsInstantiated_thenNoExceptions(){
}
}


We’re specifying the Java configuration classes with the @ContextConfiguration annotation. The new AnnotationConfigContextLoader loads the bean definitions from the @Configuration classes.

Notice that the WebConfig configuration class was not included in the test because it needs to run in a servlet context, which is not provided.


Spring Boot provides several annotations to set up the Spring ApplicationContext for our tests in a more intuitive way.

We can load only a particular slice of the application configuration, or we can simulate the whole context startup process.

For instance, we can use the @SpringBootTest annotation if we want the entire context to be created without starting the server.

With that in place, we can then add the @AutoConfigureMockMvc to inject a MockMvc instance and send HTTP requests:


@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class FooControllerAppIntegrationTest {


    @Autowired
    private MockMvc mockMvc;


    @Test
    public void whenTestApp_thenEmptyResponse() throws Exception {
            this.mockMvc.perform(get(“/foos”)
                        .andExpect(status().isOk())
                        .andExpect(...);
            }

} 


To avoid creating the whole context and test only our MVC Controllers, we can use @WebMvcTest:


@RunWith(SpringRunner.class)
@WebMvcTest(FooController.class)
public class FooControllerWebLayerIntegrationTest {


        @Autowired
        private MockMvc mockMvc;


        @MockBean
        private IFooService service;


        @Test()
        public void whenTestMvcController_thenRetrieveExpectedResult() throws Exception {
        // ...


        this.mockMvc.perform(get(“/foos”)
        .andExpect(...);
    }

 



 

Post a Comment (0)
Previous Post Next Post