1. 程式人生 > >SpringMvc單元測試

SpringMvc單元測試

現在越來越多的現實開發中,我們是先有需求,然後根據我們想要的樣子去開發。

這裡引入一個概念交測試驅動開發,我們按照需求先寫一個自己預期結果的測試用例,不然不斷的編碼和重構,最終讓測試用例通過測試,

這樣才能保證軟體的質量和可控性。

直接看例子,註解都已經寫的比較詳細了。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyMvcConfig.class})
@WebAppConfiguration("src/main/resources")//宣告載入的ApplicationContext是一個WebApplicationContext。
public class TestControllerIntegrationTests { private MockMvc mockMvc;//模擬mvc物件 @Autowired private DemoService demoService; @Autowired WebApplicationContext wac;//可注入WebApplicationContext @Autowired MockHttpSession session;//可注入模擬的http session @Autowired MockHttpServletRequest request; @Before public void
setup(){//初始化工作 this.mockMvc= MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void testNormalController() throws Exception{ mockMvc.perform(get("/normal"))//模擬向/normal進行get請求 .andExpect(status().isOk())//預期控制返回狀態為200 .andExpect(view().name("page"))//預期控制返回狀態為200 .andExpect(forwardedUrl
("/WEB-INF/classes/views/page.jsp"))//預期頁面轉向的真正路徑 .andExpect(model().attribute("msg",demoService.saySomething()));//預期model中的值 } @Test public void testRestController() throws Exception{ mockMvc.perform(get("/testRest")) .andExpect(status().isOk()) .andExpect(content().contentType("text/plain;charset=UTF-8"))//預期返回型別 .andExpect(content().string(demoService.saySomething()));//預期返回值的內容 } }