How to do it...

Let us test some existing controllers in ch03 by performing the following steps:

  1. 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(); } }
  1. 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()); 
          } 
  1. 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")); 
} 
  1. Run the test method and observe what happens.
..................Content has been hidden....................

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