温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用MockMvc测试SpringMVC Controller

发布时间:2020-04-30 12:59:10 来源:网络 阅读:10799 作者:zbzbzb022 栏目:软件技术

MockMvc 是springTest提供的对SpringMvc提供的测试工具。这样可以让单元测试不仅仅局限于对Dao和Service 层的测试。同时,也可以测试Controller层。丰富的单元测试的功能。测试时不用频繁重启servlet容器,简化了测试操作。

MockMvc需要ServletContext来模拟用户的请求和相应。


首选,需要在测试类头部添加一下Annotation

@WebAppConfiguration
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration(locations = { "classpath:spring/applicationContext.xml" })

@WebAppConfiguration 用来引入servletContext

接下来就可以在junit中编写测试类了。

demo 1 有请求头、无参数的get请求

样例代码如下:

@Test
	public void 测试类() 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 有请求头、有请求体的post请求

样例代码如下:

@Test
	public void 测试类() 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)//请求体时json
				.header("Timestamp", "1496656373791")
				.header("AppId", "1003")
				.content(jsonRequest));
		reaction.andExpect(MockMvcResultMatchers.status().isOk());
		MvcResult mvcResult =reaction.andReturn();
		System.out.println(mvcResult.getResponse().getContentAsString());
	}


以上两个例子就能基本覆盖解决使用springtest的MockMvc对Controller进行单元测试的需求。


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI