spring mvc + junit servlet 單元測試
阿新 • • 發佈:2018-11-05
// spring 版本:4.2.3 // junit 版本:4.12 import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder; import java.net.URI; /** * @Author
[email protected] * @Version 0.0.1Ø * @Date 2018/9/12 下午7:11 **/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring-servlet.xml") public class HomeControllerTest { private final String ACTION_NAME_INDEX = "/index"; private final String VIEW_NAME_INDEX = "home/index"; @Test public void indexTest() throws Exception { HomeController controller = new HomeController(); StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(controller); MockMvc mvc = builder.build(); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI.create(ACTION_NAME_INDEX)); requestBuilder.param("id", "QQ"); ResultActions actions = mvc.perform(requestBuilder); ResultMatcher matcher = MockMvcResultMatchers.view().name(VIEW_NAME_INDEX); actions.andExpect(matcher); matcher = MockMvcResultMatchers.model().attribute("cfg_name", "MAMA_HAHA"); actions.andExpect(matcher); matcher = MockMvcResultMatchers.model().attribute("id", "QQ"); actions.andExpect(matcher); matcher = MockMvcResultMatchers.request().attribute("req_name", "KAKA_XIYA"); actions.andExpect(matcher); } } // home controller import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; /** * @Author[email protected] * @Version 0.0.1 * @Date 2018/9/11 下午6:33 **/ @Controller public class HomeController { @RequestMapping("/index") public String index(Model model, HttpServletRequest request, @RequestParam(name = "id", defaultValue = "") String id){ model.addAttribute("cfg_name", "MAMA_HAHA"); request.setAttribute("req_name", "KAKA_XIYA"); model.addAttribute("id", id); return "home/index"; } }