Spring MVC Test Framework is build on Servlet API mock objects (also provided by Spring in package: org.springframework.mock.web ) and hence does not use a running Servlet container.
Prepare the test class
We have to use three annotations in our test class as shown:
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.context.ContextConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class MyMvcControllerTest {
....
}
@RunWith is a JUnit annotation, which can be used to replace default test runner org.junit.runners.BlockJUnit4ClassRunner .
SpringJUnit4ClassRunner extends default test runner BlockJUnit4ClassRunner
@WebAppConfiguration is used to specify that WebApplicationContext should be loaded for the test.
@ContextConfiguration is to used to specify how to load spring bean metadata. In above example we are loading it from our @Configuration annotated class MyWebConfig
Setting up @Before objects
In @Before method, we need to initialize Spring specific mock object: MockMvc which is the main entry point for server-side Spring MVC test support.
public class MyMvcControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
MockMvcBuilders is the main class to to access a specific implementation of MockMvcBuilder (an interface).
Write @Test Method
Here we have to take help of two builder classes:
MockMvcRequestBuilders : This class helps building MockHttpServletRequest
MockMvcResultMatchers : This class helps building a ResultMatcher which matches the result of an executed request against some expectation.
@Test
public void testMyMvcController() throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
ResultMatcher msg = MockMvcResultMatchers.model()
.attribute("msg", "Spring quick start!!");
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/");
this.mockMvc.perform(builder)
.andExpect(ok)
.andExpect(msg);
}
Here is our controller:
@Controller
public class MyMvcController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String prepareView(Model model) {
model.addAttribute("msg", "Spring quick start!!");
return "my-page";
}
}
Example ProjectDependencies and Technologies Used: - Spring Web MVC 4.2.4.RELEASE: Spring Web MVC.
- Java Servlet API 3.0.1
- Spring TestContext Framework 4.2.4.RELEASE: Spring TestContext Framework.
- JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- JDK 1.8
- Maven 3.0.4
|