Let us test some existing controllers in ch03 by performing the following steps:
- Create another test class inside org.packt.dissect.mvc.test without loading WebApplicationContext and configure MockMvc to test only SimpleController of this project:
import static org.springframework.test.web.servlet.request.
MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.
MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.
MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.
MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.
MockMvcResultMatchers.view; @RunWith(MockitoJUnitRunner.class) public class TestControllerConfiguration { private MockMvc mockMvc; @Before public void setUp() { this.mockMvc = MockMvcBuilders.standaloneSetup(new
SimpleController()).build(); } }
- Add some test cases on the controller's GET and POST request handlers:
@Test public void testGetPage() throws Exception { mockMvc.perform(get("/simple.html")).andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("get")); } @Test public void testPostPage() throws Exception { mockMvc.perform(post("/simple.html")) .andExpect(view().name("post")) .andDo(print()) .andExpect(status().isOk()); }
- Add another test case that will test a non-existent component or a handler request that is not found inside SimpleController.
@Test public void testOtherRequest() throws Exception { mockMvc.perform(get("/login.html")).andDo(print()) .andExpect(view().name("login")); }
- Run the test method and observe what happens.