Integration testing Spring controllers

In the flows we discussed, we looked at using real unit tests--ones that only load up the specific controllers that are being tested.

Another possibility is to load up the entire Spring context. However, this would be more of an integration test as we would load up the entire context. The following code shows you how to do a complete launch of a Spring context, launching all controllers:

    @RunWith(SpringRunner.class) 
@WebAppConfiguration
@ContextConfiguration("file:src/main/webapp/
WEB-INF/user-web-context.xml")
public class BasicControllerSpringConfigurationIT {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc =
MockMvcBuilders.webAppContextSetup
(this.wac).build();
}
@Test
public void basicTest() throws Exception {
this.mockMvc
.perform(
get("/welcome")
.accept(MediaType.parseMediaType
("application/html;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().string
("Welcome to Spring MVC"));
}
}

A few things to note are as follows:

  • @RunWith(SpringRunner.class): SpringRunner helps us launch a Spring context.
  • @WebAppConfiguration: Used to launch a web app context with Spring MVC
  • @ContextConfiguration("file:src/main/webapp/WEB-INF/user-web-context.xml"): Specifies the location of the spring context XML.
  • this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(): In the earlier examples, we used a standalone setup. However, in this example, we want to launch the entire web app. So, we use webAppContextSetup.
  • The execution of the test is very similar to how we did it in earlier tests.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset