基于Spring-WS的Restful API的集成测试
在很多Java企业级应用中,Spring占据了非常重要的位置,这就导致了基本上的技术选型都是围绕着Spring来, 比方说笔者最近的项目需要开发一个Restful的API接口,选型的时候就说,客户架构师直接就拍了spring-ws,原因呢?系统中其他的模块都是用的Spring-ws,保持一致,而且社区活跃,文档丰富,遇到问题易解决。好了,入正题。
既然选定了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
基于Spring-WS的Restful API的集成测试的更多相关文章
- 基于Spring Boot的RESTful API实践(一)
1. RESTful简述 REST是一种设计风格,是一组约束条件及原则,而遵循REST风格的架构就称为RESTful架构,资源是RESTful的核心,一个好的RESTful架构,通过URL就能很 ...
- 使用Spring MVC开发RESTful API
第3章 使用Spring MVC开发RESTful API Restful简介 第一印象 左侧是传统写法,右侧是RESTful写法 用url描述资源,而不是行为 用http方法描述行为,使用http状 ...
- 使用 node-odata 轻松创建基于 OData 协议的 RESTful API
前言 OData, 相信身为.NET程序员应该不为陌生, 对于他的实现, 之前也有童鞋进行过介绍(见:这里1,这里2). 微软的WCF Data Service即采用的该协议来进行通信, ASP.NE ...
- spring jwt springboot RESTful API认证方式
RESTful API认证方式 一般来讲,对于RESTful API都会有认证(Authentication)和授权(Authorization)过程,保证API的安全性. Authenticatio ...
- Spring Boot构建RESTful API与单元测试
如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下相关的内容. @Controller:修饰class,用来创建处理http请求的对象 @RestController:Spr ...
- 使用 Spring Boot 构建 RESTful API
1. 使用 Idea 创建 Spring Initializer 项目 在创建项目的对话框中添加 Web 和 Lombok,或者建立项目后在 pom.xml 中添加依赖: <dependency ...
- Spring Boot中Restful Api的异常统一处理
我们在用Spring Boot去向前端提供Restful Api接口时,经常会遇到接口处理异常的情况,产生异常的可能原因是参数错误,空指针异常,SQL执行错误等等. 当发生这些异常时,Spring B ...
- Spring Boot构建RESTful API
@Controller:修饰class,用来创建处理http请求的对象 @RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseB ...
- 用Kotlin写一个基于Spring Boot的RESTful服务
Spring太复杂了,配置这个东西简直就是浪费生命.尤其在没有什么并发压力,随便搞一个RESTful服务 让整个业务跑起来先的情况下,更是么有必要纠结在一堆的XML配置上.显然这么想的人是很多的,于是 ...
随机推荐
- HTML 布局
网站布局 大多数网站会把内容安排到多个列中(就像杂志或报纸那样). 大多数网站可以使用 <div> 或者 <table> 元素来创建多列.CSS 用于对元素进行定位,或者为页面 ...
- NSNotificationCenter机制
作用:NSNotificationCenter是专门供程序中不同类间的消息通信而设置的. 注册通知:即要在什么地方接受消息 [[NSNotificationCenter defaultCenter] ...
- SQLSERVER如何导入数据保持ID不变(ID为自增主键)
使用SQL SERVER最操蛋的就是导入数据,以前用企业管理器直接导数据,导一次骂N次娘,在骂了微软无数次娘之后总结了一个方法揍合着还算受用. 其核心要点就是要将数据结构导入到目标数据库服务器上,再来 ...
- POJ2187(旋转卡壳)
Beauty Contest Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 35459 Accepted: 10978 ...
- [转载]【虚拟化系列】VMware vSphere 5.1 网络管理
转载自:http://mabofeng.blog.51cto.com/2661587/1020375 网络是VMware vSphere 5.1的基础,所有虚拟机都需要网络来进行通信.如果将所有的虚拟 ...
- gulp源码解析(三)—— 任务管理
上篇文章我们分别对 gulp 的 .src 和 .dest 两个主要接口做了分析,今天打算把剩下的面纱一起揭开 —— 解析 gulp.task 的源码,了解在 gulp4.0 中是如何管理.处理任务的 ...
- 记一次阿里云Linux服务器安装.net core sdk的问题以及解决方法
因为公司领导要求新的项目能跨平台部署,也就是说能部署到Linux服务器上,故新的项目采用了Asp.net mvc core 1.1 进行开发.开发过程一切都比较顺利,然后在之前申请试用的一台微软Azu ...
- HUST 1541 Student’s question
1541 - Student’s question 时间限制:1秒 内存限制:128兆 696 次提交 134 次通过 题目描述 YYis a student. He is tired of calc ...
- 使用ViewPagerAdapter 页面引导适配器设置app启动页,引导页面的实现
一般的app第一次安装启动的时候,都会有一个启动页面和引导页的画面,然后才进入主程序.anndroid中的ViewPagerAdapter 是一个继承与PageAdapter的 页面引导适配器.由于我 ...
- OSS项目进度(2.19)
前两周先后完成了OSS.Common ,OSS.Http ,OSS.Social 项目的.net standard支持,再次开始进入框架本身的开发,今天进度情况: 一.OSS.Social 完成摇一摇 ...