MockMvc 是springTest提供的對(duì)SpringMvc提供的測(cè)試工具。這樣可以讓單元測(cè)試不僅僅局限于對(duì)Dao和Service 層的測(cè)試。同時(shí),也可以測(cè)試Controller層。豐富的單元測(cè)試的功能。測(cè)試時(shí)不用頻繁重啟servlet容器,簡(jiǎn)化了測(cè)試操作。

MockMvc需要ServletContext來(lái)模擬用戶的請(qǐng)求和相應(yīng)。
選,需要在測(cè)試類頭部添加一下Annotation
@WebAppConfiguration
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration(locations = { "classpath:spring/applicationContext.xml" })@WebAppConfiguration 用來(lái)引入servletContext
接下來(lái)就可以在junit中編寫測(cè)試類了。
demo 1 有請(qǐng)求頭、無(wú)參數(shù)的get請(qǐng)求
樣例代碼如下:
@Test
public void 測(cè)試類() throws Exception {
ResultActions reaction=this.mockMvc.perform(MockMvcRequestBuilders.get("/service/test/testController")
.accept(MediaType.APPLICATION_JSON)//返回值接收json
.header("Timestamp", "1496656373783")
.header("AppId", "1003"));
reaction.andExpect(MockMvcResultMatchers.status().isOk());
MvcResult mvcResult =reaction.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}demo 2 有請(qǐng)求頭、有請(qǐng)求體的post請(qǐng)求
樣例代碼如下:
@Test
public void 測(cè)試類() throws Exception {
PolicyInfoRequest request=new PolicyInfoRequest();
request.setAnnualPremium(100);
request.setPolicyNo("Test-222");
request.setPolicyRebate(0.28f);
request.setPolicyType(1);
request.setRebateAmount(28f);
String jsonRequest=JSON.toJSONString(request);
ResultActions reaction =this.mockMvc.perform(MockMvcRequestBuilders.post("/policy/info/save")
.contentType(MediaType.APPLICATION_JSON)//請(qǐng)求體時(shí)json
.header("Timestamp", "1496656373791")
.header("AppId", "1003")
.content(jsonRequest));
reaction.andExpect(MockMvcResultMatchers.status().isOk());
MvcResult mvcResult =reaction.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}以上兩個(gè)例子就能基本覆蓋解決使用springtest的MockMvc對(duì)Controller進(jìn)行單元測(cè)試的需求。
分享題目:使用MockMvc測(cè)試SpringMVCController-創(chuàng)新互聯(lián)
文章網(wǎng)址:http://www.chinadenli.net/article6/dccjig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、企業(yè)建站、關(guān)鍵詞優(yōu)化、標(biāo)簽優(yōu)化、網(wǎng)站建設(shè)、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容