- 浏览: 1030031 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
繁星水:
Useful!!
Object-C之(Null)与(Bool) -
pacer123:
请问注解@ApiModelProperty 在哪个jar包下面 ...
Micro Service工具集之Swagger:可测试的样式化API文档 -
sucheng2016:
这东东真的好用么/
对象转换利器之Dozer -
zzq0324:
http://git.oschina.net/zzq0324/ ...
基于Spring-WS的Restful API的集成测试 -
lrz0534:
你好,我在maven上面下载了swagger-springmv ...
Micro Service工具集之Swagger:可测试的样式化API文档
在很多Java企业级应用中,Spring占据了非常重要的位置,这就导致了基本上的技术选型都是围绕着Spring来, 比方说笔者最近的项目需要开发一个Restful的API接口,选型的时候就说,客户架构师直接就拍了spring-ws,原因呢?系统中其他的模块都是用的Spring-ws,保持一致,而且社区活跃,文档丰富,遇到问题易解决。好了,入正题。
既然选定了Spring-WS, 已经TDD入魔的我,首先想到的就是我应该怎么测试这个API接口呢? 作为业界最成熟的框架,Spring为测试其Web应用提供了非常好用的辅助类MockMvc。
首先,在项目的测试代码中加入辅助Spring Web测试的库
然后,编写测试代码
testPost方法中的print()语句打印出的效果如下:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /requests
Parameters = {userId=[xianlinbox]}
Headers = {Content-Type=[application/json], Accept=[application/json]}
Handler:
Type = com.xianlinbox.api.ApiController
Method = public com.xianlinbox.api.Request com.xianlinbox.api.ApiController.post(java.lang.String,java.lang.String)
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 201
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"userId":"xianlinbox","requestId":"1","requestType":"POST","message":"this is the message"}
Forwarded URL = null
Redirected URL = null
Cookies = []
看完了测试, 来简单的看下具体的实现代码:
该Demo的所有代码: https://github.com/xianlinbox/TDD_Demo/tree/master/spring-ws-rest
既然选定了Spring-WS, 已经TDD入魔的我,首先想到的就是我应该怎么测试这个API接口呢? 作为业界最成熟的框架,Spring为测试其Web应用提供了非常好用的辅助类MockMvc。
首先,在项目的测试代码中加入辅助Spring Web测试的库
testCompile( "org.springframework:spring-test:$springVersion", "org.springframework.ws:spring-ws-test:2.1.0.RELEASE", "javax.servlet:javax.servlet-api:3.0.1", "com.jayway.jsonpath:json-path-assert:0.9.0" )其中,jsonpath库的依赖是为了更好的做json格式数据的断言。
然后,编写测试代码
//指定使用SpringIntegration测试,并且制定了运行测试的ApplicationContext @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-servlet.xml"}) public class ApiControllerIntegrationTest { @Autowired private ApiController controller; private MockMvc mockMvc; @Before public void setUp() throws Exception { //绑定需要测试的Controller到MockMvcshang mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } @Test public void testGet() throws Exception { //发出请求,在请求中可以设置一个http request可设置的所有参数 mockMvc.perform(get("/requests/1") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .param("userId", "xianlinbox") ) //验证Respondse,status()中,可验证所有的HTTP Status CODE //另外,使用了jsonPath更优雅的做json属性值的验证 .andExpect(status().isOk()) .andExpect(jsonPath("$.userId").value("xianlinbox")) .andExpect(jsonPath("$.requestId").value("1")) .andExpect(jsonPath("$.requestType").value("GET")); } @Test public void testPost() throws Exception { mockMvc.perform(post("/requests") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("this is the message") .param("userId", "xianlinbox") ) //使用print()可打印出当前测试设计的HTTP Request/Responsed的所有信息,方便定位问题 //Post方法的返回结果应该是202(HttpStatus.Created),对象创建成功 .andDo(print()) .andExpect(status().isCreated()) .andExpect(jsonPath("$.userId").value("xianlinbox")) .andExpect(jsonPath("$.requestType").value("POST")) .andExpect(jsonPath("$.message").value("this is the message")); } }
testPost方法中的print()语句打印出的效果如下:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /requests
Parameters = {userId=[xianlinbox]}
Headers = {Content-Type=[application/json], Accept=[application/json]}
Handler:
Type = com.xianlinbox.api.ApiController
Method = public com.xianlinbox.api.Request com.xianlinbox.api.ApiController.post(java.lang.String,java.lang.String)
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 201
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"userId":"xianlinbox","requestId":"1","requestType":"POST","message":"this is the message"}
Forwarded URL = null
Redirected URL = null
Cookies = []
看完了测试, 来简单的看下具体的实现代码:
@Controller public class ApiController { @RequestMapping(value = "/requests/{requestId}", method = RequestMethod.GET) @ResponseBody public Request get(@PathVariable String requestId, @RequestParam(value = "userId") String userId) { return new Request(userId, requestId, "GET"); } @RequestMapping(value = "/requests", method = RequestMethod.POST) @ResponseBody @ResponseStatus(value = HttpStatus.CREATED) public Request post(@RequestParam(value = "userId") String userId, @RequestBody String content) { Request request = new Request(userId, "1", "POST"); request.setMessage(content); return request; } }
- 使用RequestMapping定义URL
- 使用@ResponseBody表示返回json
- 使用@PathVariable 获取路径参数
- 使用@RequestParam获取request payload中的参数
- 使用@RequestBody获取request body
- 使用@ResponseStatus(value = HttpStatus.CREATED),定义返回的HTTP STATUS CODE
该Demo的所有代码: https://github.com/xianlinbox/TDD_Demo/tree/master/spring-ws-rest
发表评论
-
关于并发的思考
2015-02-08 22:33 4271并发数 并发数和2个因 ... -
使用Hystrix守护应用(3)
2015-01-02 22:04 12826监控HystrixCommand 除了隔离依赖服务的调用外,H ... -
使用Hystrix守护应用(2)
2014-12-30 14:35 16762接上篇(http://ningandjiao.iteye.co ... -
使用Hystrix守护应用(1)
2014-12-30 14:28 15188Hystrix(https://github.com/Netf ... -
Mac下同时安装多个版本的JDK
2014-04-14 21:42 33120JDK8 GA之后,小伙伴们喜大普奔,纷纷跃跃欲试,想体验一下 ... -
性能测试工具之Gatling
2014-01-15 19:27 17224Gatling一直是久闻其名但 ... -
JavaMail测试工具之GreenMail
2014-01-08 19:13 7323不管现在各种Mock框架的运用有多广,我个人在写单元测试的时候 ... -
定制一个Gradle Plugin --- project-structure
2014-01-03 21:23 8413最近在项目中遇到一个 ... -
Restful Spring MVC应用的Request验证
2013-12-26 15:05 23301在开放平台的时候,尤其是坐Rest服务的时候,因为用户可以给你 ... -
Spring MVC中的异常处理
2013-12-25 13:13 24103在一个良好的Rest架构的应用中,所有的异常都应该有对应的Ht ... -
Spring 4.0升级小贴士
2013-12-22 19:40 11393随着Spring4.0的发布,很多同志估计都在考虑升级的事情了 ... -
Spring4.0给我们带来什么?
2013-12-22 17:13 44960JDK8 对JDK8的支持,这个目前来说还是探索性质,毕竟Ja ... -
RESTful API版本控制策略
2013-12-15 19:51 31607做RESTful开放平台,一方面其API变动越少, 对API调 ... -
对象转换利器之Dozer
2013-12-14 22:46 19783在Java的世界中,经常会 ... -
TDD Of Spring JMS
2013-11-25 19:53 1702不知何时养成了习惯,在没有一个可运行的测试的时候,个人完全没有 ... -
Micro Service工具集之Swagger:可测试的样式化API文档
2013-09-28 19:55 44658在我之前的一篇博文中,介绍了Yammer开发团队贡献的开源微服 ... -
进击的Java开发
2013-07-14 20:48 5851今天在公司的邮件组中看到一组很有趣的讨论,这是我最喜欢目前公司 ... -
说说SpringBatch的领域概念
2013-06-21 20:32 3578谈到Spring Batch,会谈到 ... -
做项目时需要考虑的安全性问题
2013-04-16 20:20 4724在开发一个项目的时候,大家经常会忽略项目的安全性问题,有很多的 ... -
使用Gradle部署jar包到Maven中央库
2013-04-12 16:15 24085Maven作为目前Java界最好的Dependency管理系统 ...
相关推荐
spring-boot-web代码示例,是IDEA的项目工程,使用restful风格实现增删查改,静态数据
springboot2.4增删改查示例,结合B站尚硅谷教程使用,给初学者使用,spingboot2.4相较于1.5版本的用法有些变化,经验者绕行。
python开发,基于flask-restful 的中小型项目,restful风格API接口开发实例,以mongodb作为数据库 python开发,基于flask-restful 的中小型项目,restful风格API接口开发实例,以mongodb作为数据库python开发,基于...
毕业设计-基于Restful API的项目实施管理系统.zip
laravel-restful-api-starter, 使用 Laravel 和MongoDB构建一个 RESTful API #Laravel Restful API启动程序现在查看一下 WIKI !欢迎捐赠对于代码和 doc: ) !是什么?这里启动器基于以下功能:Laravel 4.2: 使用轻...
java-spring-boot-restful-api Magazine API - 宁静的 API 示例。 堆 Java 8 日本特许经营协会 弹簧靴 JUnit - Mockito Gradle 先决条件 JDK 1.8 等级 2.2.1 任何 REST 客户端(如 XHR 海报) 可选:GGTS(或...
主要介绍了Python中Flask-RESTful编写API接口(小白入门),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Hands-On RESTful API Design Patterns and Best Practices
java-spring-mongo-restful-api Magazine API - 宁静的 API 示例。堆Java 8 Mongo (NoSQL 数据库) 弹簧靴JUnit - Mockito Gradle先决条件JDK 1.8 等级 2.2.1 mongo(启动并运行) 任何 REST 客户端(如 XHR 海报) ...
Hands-On RESTful API Design Patterns and Best Practices 副标题 Design, Develop, and Deploy Highly Adaptable, Scalable, and Secure RESTful Web APIs 作者 Harihara Subramanian and Pethuru Raj 出版社 ...
上传文件春天启动 使用Spring-Boot RESTful API和Hibernate上传和下载文件 UNI项目,用于使用Spring,Hibernate,JQUERY,MYSQL上传和下载所有类型的文件(包括照片)
带RESTful API的自托管文档转换服务
restit - 一个Go 微型框架帮助编写RESTful API集成测试。一个Go库帮助你测试你的RESTful API应用
Flask-SQLALchemy-RESTFUL-API, 带有 Flask 和 Sqlalchemy的RESTFUL JSON API 教程和解释http://techarena51.com/index.php/buidling-a-database-driven-restful-json-api-in-python-3-with-flask-flask-restful
与Activiti,Drools,LDAP,MySQL,带有SwaggerUI的Restful API,AngularJS + Ionic等的Spring-boot集成。 什么? 使用SpringBoot框架来设置RESTful API包装Activiti API。 并使用Swagger-UI可视化RESTful API,...
Api-nodejs-restful-api.zip,如何使用nodejs创建restful crud api?nodejs restful api,一个api可以被认为是多个软件设备之间通信的指导手册。例如,api可用于web应用程序之间的数据库通信。通过提取实现并将数据...
yii2-advanced-api, 具有 RESTful API设置的Yii2高级模板 2高级应用程序模板中的 rest APIYii2高级应用程序模板,配置了 RESTful... 查看 http://budiirawan.com/setup-restful-api-yii2/ 了解更详细的解释安装 Compose
Java SpringBoot 课程 restful crud 实验资源 ...GitHub中有源码 https://github.com/kevinkda/MarkdownRepository/tree/master/Develop%20Demo/Java%20Framework/Spring/SpringBoot/spring-boot-restful-crud-01