首页 > 编程知识 正文

mockmvc传递对象,springmvc单元测试

时间:2023-05-06 00:42:02 阅读:40379 作者:387

出现的问题:我们在后台开发接口时,经常做的一件事是编码、启动后台服务、使用博士后或其他接口调用工具进行测试,以及接口问题如果继续这样的流程,就我个人而言,启动服务是一件非常麻烦的事情,需要看我写的界面是否正确的时候,每次都必须重新启动,输入参数,访问服务。 而且,在本地的时候代码完全没有问题地跑着。 部署到支持环境时,明明封装没有问题,但接口却不通了。 这种接口不通的问题在编译打包时暴露出来,不是可以节省很多时间吗? 如果查看最近springboot附带的MockMVC,应该属于SpringMVC的测试框架。

问题解决方案:默认情况下,查看springboot官方文档时,@springbootTest注释不会启动服务器。 如果要在此模拟环境中测试web端点,可以单独配置MockMvc:

这里使用用maven构建的springboot项目,生成成功时在src/test/.下对应自动生成的测试类

@runwith(springrunner.class ) springboottest @ autoconfiguremockmvc//此评论用于mockMvc的单元测试publiccclasslogdemoapplicatic

@getmapping(/testget ) ) public MapString,objecttestget ) @requestparam ) (name ) (String name,@requestparam ) ) ) map.put('name ',name ); map.put('age ',age ); map.put(status ),200 ); 返回图; }对应的单元测试:

importstaticorg.spring framework.test.web.servlet.request.mockmvcrequestbuilders.get; @Test public void testGet () throws exception (system.out.println )=======() ) ) //其中get (对于静态方法,为web.servlet包下的mvcresultmvcresult=this.MVC.perform (get (/test get ) )/get请求system.out.println (MVC result.getresponse ().getContentAsString ) ); //响应结果system.out.println((=======测试获取结束=============() () ) ) ) ) ) )

更正代码,如果测试过程中出现错误:

@Test public void testGet () throws exception (system.out.println )=======() ) ) this.MVC.perform(get(/testget ).param )、(温柔板栗)、(param )、(14 ) )、andexpect )、Statuture //结果是否如预期system.out.println (MVC result.getresponse (.get content asstring ) ) ) ) 65系统. out.) }错误提示:

请求和响应信息打印在控制台上,也有助于查找错误。 这里的错误是因为接口的返回值与预期的不同。 安卓系统

t(content().string("result")); 这个表示我们的预期结果值是result,但是返回值是一个json,所以会报错,利用这种方法测试要慎用,因为很多时候一个接口返回的数据并不是一样的,格式是一样的,但是值可以发生变化,所以可以用Http响应的状态来判断,也可以使用自己定义的接口状态来判断。

其他的接口请求方式略有不同,但是大致的API都还是一样的。

GET请求传JSON示例:

//接口@GetMapping("/testGetJson") public Map<String,Object> testGetJson(@RequestBody User user ){ Map<String,Object> map = new HashMap<>(); map.put("user",JSONObject.toJSONString(user)); map.put("status",200); return map; }//单元测试 @Test public void testGetJson() throws Exception { System.out.println("=======开始测试testGetJSON======="); String result = this.mvc.perform( get("/testGetJson") .content("{"id":1,"name":"温柔的板栗","sex":"男"}") .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); System.out.println("result"+result); System.out.println("=======开始测试testGetJSON======="); }

使用POST方式的 @PathVariable注解传参

//示例接口@PostMapping("/testPost/{id}") public String testPost(@PathVariable ("id")Integer id){ return "this testPost return " +id; }//测试用例 @Test public void testPost() throws Exception { System.out.println("=============开始测试testPost============"); int id = 1; this.mvc .perform(post("/testPost/"+id)) .andExpect(status().isOk()) .andExpect(content().string("this testPost return " +id)); System.out.println("==============测试testPost结束=============="); }

使用POST方式传输JSON格式的数据与GET基本一致,这里无需重复演示

使用POST方式接受表单数据

//接口 @PostMapping("/testPostForm") public Map<String,Object> testPostForm(User user){ Map<String,Object> map = new HashMap<>(); map.put("user",JSONObject.toJSONString(user)); map.put("status",200); return map; }// 单元测试 @Test public void testPostForm() throws Exception { System.out.println("===========开始测试testPostForm==============="); String result = this.mvc.perform( post("/testPostForm") .param("id", "1") .param("name", "温柔的板栗") .param("sex", "男") .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); System.out.println("result :" + result); System.out.println("===============测试testPostForm结束================="); }

param中的values是可变参数,可以传数组,对于Json的传参,最好直接用fastJson转换成字符串,用变量传输.

header中的传参一般都是必不可少的,在上边的接口加以改造即可:

// 接口 @PostMapping("/testPostForm") public Map<String,Object> testPostForm(User user,@RequestHeader ("token") String token){ Map<String,Object> map = new HashMap<>(); map.put("user",JSONObject.toJSONString(user)); map.put("token",token); map.put("status",200); return map; }// 单元测试 @Test public void testPostForm() throws Exception { System.out.println("===========开始测试testPostForm==============="); String result = this.mvc.perform( post("/testPostForm") .param("id", "1") .param("name", "温柔的板栗") .param("sex", "男") .header("token","this is a token") .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); System.out.println("result :" + result); System.out.println("===============测试testPostForm结束================="); }

当然,这种测试框架不止一个,在官方文档中还有 WebTestClient 等等,大家有兴趣的可以自己看看

在打包的时候可以执行测试,查看接口返回值是否有问题:

测试输出内容可以自定义,可以打印更多的信息

附录:

MockMvc的官方文档地址:

https://docs.spring.io/spring-boot/docs/2.1.4.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-mock-environment

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。