Controller層html
@Controller public class BookController { @Autowired private BookService bookService; private static final Log logger = LogFactory.getLog(BookController.class); @RequestMapping(value = "/book_edit/{id}") public String editBook(Model model, @PathVariable long id) { System.out.println(id); Book book = bookService.get(id); model.addAttribute("book", book); return "BookEditForm"; } @RequestMapping(value = "/book_save" ,method = RequestMethod.POST) public String saveBook(@ModelAttribute Book book) { //bookService.save(book); return "redirect:/book_list"; } @RequestMapping(value = "/book_list",method = RequestMethod.GET) public String listBooks(Model model) { logger.info("book_list"); System.out.println("book_list start excute!!"); List<Book> books = bookService.getAllBooks(); model.addAttribute("books", books); return "BookList"; } }
模擬的測試類java
package cm.yanxi.test; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.view.InternalResourceViewResolver; <!---這幾個常量很重要,必須引入--> 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.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; /** * Created by 言溪 on 2016/11/10. */ @RunWith(SpringJUnit4ClassRunner.class) //表示測試環境使用的ApplicationContext將是WebApplicationContext類型的;value指定web應用的根 @WebAppConfiguration("src/main/webapp") @ContextConfiguration(locations = {"classpath:spring-common.xml","classpath:spring-mvc.xml"}) public class BookControllerTest { // 注入web環境的ApplicationContext容器 @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; @Before public void setup() throws Exception{ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/html/"); viewResolver.setSuffix(".jsp"); this.mockMvc=webAppContextSetup(this.webApplicationContext).build(); } @Test public void saveBookTest() throws Exception { this.mockMvc.perform( post("/book_save") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("category","計算機科學") .param("title","大數據集羣") .param("author","kangkang") .param("isbn","123456")) .andDo(print()) .andExpect(redirectedUrl("/book_list")) .andReturn(); } @Test public void BookListTest() throws Exception { this.mockMvc.perform(get("/book_list")) .andDo(print()) .andExpect(view().name("BookList")) .andReturn(); } @Test public void BookEditTest() throws Exception { this.mockMvc.perform(get("/book_edit/{id}","3")) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("BookEditForm")) .andExpect(model().attribute("book","")) .andReturn(); } }
更多的模擬請求案例點這裏git
##解釋一下幾個參數的含義github
測試結果顯示web
MockHttpServletRequest: HTTP Method = GET Request URI = /book_edit/3 Parameters = {} Headers = {} Handler: Type = com.yanxi.controller.BookController Method = public java.lang.String com.yanxi.controller.BookController.editBook(org.springframework.ui.Model,long) Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = BookEditForm View = null Attribute = book value = Book{id=3, isbn='9787115386397', title='HTML5實戰', category='計算機編程', author='Marco Casario'} errors = [] FlashMap: Attributes = null MockHttpServletResponse: Status = 200 Error message = null Headers = {} Content type = null Body = Forwarded URL = /html/BookEditForm.jsp Redirected URL = null Cookies = []