Testing the Spring Context
Starting with Spring 3.1, we get first-class testing support for @Configuration classes:
@ContextConfiguration(
classes = {WebConfig.class, PersistenceConfig.class},
loader = AnnotationConfigContextLoader.class)
public class SpringTest {
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:
@SpringBootTest
@AutoConfigureMockMvc
public class FooControllerAppIntegrationTest {
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:
@WebMvcTest(FooController.class)
public class FooControllerWebLayerIntegrationTest {
private MockMvc mockMvc;
private IFooService service;
public void whenTestMvcController_thenRetrieveExpectedResult() throws Exception {
// ...
.andExpect(...);
}
}