SpringBoot 构建RestFul API 含单元测试
相关博文:
首先,回顾并详细说明一下在快速入门中使用的
@Controller
、@RestController
、@RequestMapping
注解。如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下快速入门的内容。@Controller
:修饰class,用来创建处理http请求的对象@RestController
:Spring4之后加入的注解,原来在@Controller
中返回json需要@ResponseBody
来配合,如果直接用@RestController
替代@Controller
就不需要再配置@ResponseBody
,默认返回json格式。@RequestMapping
:配置url映射
- Controller 层
- package com.creditease.bsettle.crm.controller.user;
- import com.creditease.bsettle.crm.model.User;
- import com.creditease.bsettle.crm.service.UserService;
- import com.creditease.bsettle.crm.util.ResponseUtil;
- import com.creditease.bsettle.monitor.base.controller.BaseCommonQueryController;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.*;
- import javax.servlet.http.HttpServletRequest;
- import java.util.HashMap;
- import java.util.Map;
- @Slf4j
- @RequestMapping(value = "/v1/users")
- @RestController
- public class UserControllerRestFulDemo extends BaseCommonQueryController<User>{
- @Autowired
- UserService userService;
- @RequestMapping(value = "",method = RequestMethod.GET)
- @ResponseBody
- public Map<String, Object> pageList(HttpServletRequest request, @RequestParam Map<String, String> searchParams) {
- Map<String, Object> maps = new HashMap<String, Object>();
- try {
- //TODO do something
- //maps = userService.queryPage(searchParams);
- } catch (Exception var4) {
- log.error(var4.getMessage(), var4);
- maps.put("retCode", Boolean.valueOf(false));
- maps.put("retMessage", var4.getMessage());
- }
- return maps;
- }
- /**
- * 根据用户ID 查询用户信息
- * @param request
- * @param id
- * @return
- */
- @RequestMapping(value = "/{id}",method = RequestMethod.GET)
- @ResponseBody
- Map<String,Object> findUser(HttpServletRequest request,@PathVariable Long id) {
- Map<String,Object> resultMap = ResponseUtil.createMap(true,"操作成功!");
- try {
- //TODO do something
- /* User user = userService.findUserById(id);
- resultMap.put("user",user);*/
- }catch(Exception e){
- log.error("findUserById is Exception !!! {} \n",e);
- resultMap = ResponseUtil.createMap(false,"操作失败!"+e.getMessage());
- }
- return resultMap;
- }
- /**
- * 修改用户信息
- * @param request
- * @param user
- * @param updateType 修改类型 1:修改密码 2:修改用户信息 3:修改用户状态
- * @return
- */
- @RequestMapping(value="/{id}", method = RequestMethod.PUT)
- @ResponseBody
- Map<String,Object> updateUserInfo(HttpServletRequest request,@ModelAttribute User user,@PathVariable Long id,
- @RequestParam("updateType") int updateType){
- Map<String,Object> resultMap = ResponseUtil.createMap(true,"操作成功!");
- try{
- //TODO do something
- // userService.updateUser(user,updateType,id);
- }catch (Exception e){
- log.error("updateUserInfo is Exception !!! {} \n",e);
- resultMap = ResponseUtil.createMap(false,"操作失败!"+e.getMessage());
- }
- return resultMap;
- }
- /**
- * 根据用户ID删除用户
- * @param request
- * @param id
- * @return
- */
- @RequestMapping(value="/{id}", method = RequestMethod.DELETE)
- @ResponseBody
- Map<String,Object> delUserById(HttpServletRequest request,@PathVariable Long id){
- Map<String,Object> resultMap = ResponseUtil.createMap(true,"操作成功!");
- try{
- //TODO do something
- //userService.delete(id);
- }catch (Exception e){
- log.error("delUserById is Exception !!! {} \n",e);
- resultMap = ResponseUtil.createMap(false,"操作失败!"+e.getMessage());
- }
- return resultMap;
- }
- /**
- * 保存用户信息
- * @param request
- * @param user
- * @return
- */
- @RequestMapping(value = "", method = RequestMethod.POST)
- @ResponseBody
- Map<String,Object> saveUserInfo(HttpServletRequest request, @ModelAttribute User user){
- Map<String,Object> resultMap = ResponseUtil.createMap(true,"操作成功!");
- try{
- //TODO do something
- //userService.save(user);
- }catch (Exception e){
- log.error("saveUserInfo is Exception !!! {} \n",e);
- resultMap = ResponseUtil.createMap(false,"操作失败!"+e.getMessage());
- }
- return resultMap;
- }
- }
- View 层
- 根据查询条件获取user列表
- $.ajax({
- url: '../v1/users',
- async: false,
- type: 'GET',
- dataType: 'json
- data: {
- //TODO
- } ,
- success: function(data) {
- //TODO
- }
- });
OR
- $('#userTable').bootstrapTable({
- method: 'GET',
- url: '../v1/user',
- dataType: 'json',
- pagination: true,
- pageList: [,,,],
- pageNumber: ,
- pageSize: ,
- //singleSelect: true,
- clickToSelect: true,
- sidePagination: 'server',
- queryParams: queryParams,
- locale: 'zh-CN',
- // 略
- })
- $.ajax({
获取ID为1 的用户
- $.ajax({
- url: '../v1/user/1',
- type: 'GET',
- dataType: 'json',
- data: {
- //TODO
- },
- success: function(data) {
- //TODO
- }
- });
- $.ajax({
更新用户ID为1 的用户信息
- $.ajax({
- url: '../v1/user/1',
- type: 'PUT',
- dataType: 'json',
- data: {
- //TODO new user data
- },
- success: function(data) {
- //TODO
- }
- });
- $.ajax({
删除用户ID为1的用户
- $.ajax({
- url: '../v1/user/1',
- type: 'DELETE',
- dataType: 'json',
- data: {
- //TODO other param
- },
- success: function(data) {
- //TODO
- }
- });
- $.ajax({
- 测试用例
- package com.creditease.bsettle.crm;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import org.springframework.test.context.web.WebAppConfiguration;
- import org.springframework.test.web.servlet.MockMvc;
- import org.springframework.test.web.servlet.RequestBuilder;
- import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
- import org.springframework.test.web.servlet.setup.MockMvcBuilders;
- import org.springframework.web.context.WebApplicationContext;
- import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
- import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
- import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
- /**
- * @author mengfanzhu
- * @Package com.creditease.bsettle.crm
- * @Description:
- * @date 5/19/17 10:40
- * */
- @RunWith(SpringJUnit4ClassRunner.class)
- @SpringBootTest(classes = CrmApplication.class)
- @WebAppConfiguration
- public class UserServiceRestTest {
- @Autowired
- private WebApplicationContext wac;
- private MockMvc mvc;
- @Before
- public void setUp() throws Exception {
- // mvc = MockMvcBuilders.standaloneSetup(new UserControllerRestFulDemo()).build();
- mvc = MockMvcBuilders.webAppContextSetup(wac).build();
- }
- @Test
- public void getUserList() throws Exception {
- // 1、get查一下user列表
- RequestBuilder request = MockMvcRequestBuilders.get("/v1/users")
- .header("auth", "false")
- .param("pageNumber", "")
- .param("pageSize", "");
- mvc.perform(request)
- .andDo(print()) //print request and response to Console
- .andExpect(status().isOk())
- .andExpect(content().contentType("application/json;charset=UTF-8"));
- }
- @Test
- public void postUser() throws Exception {
- // 2、post提交一个userRequestBuilder
- RequestBuilder request = MockMvcRequestBuilders.post("/v1/user")
- .header("auth","false")
- .param("isModifyPassword","N")
- .param("status","O")
- .param("userName","testName"+System.currentTimeMillis())
- .param("userLoginPassword","aaaa1234")
- .param("mobile","")
- .param("email","fjksdfj@11.com")
- .param("crmEnterpriseId","");
- mvc.perform(request)
- .andDo(print());
- }
- @Test
- public void getUser() throws Exception {
- // get获取user列表,应该有刚才插入的数据
- RequestBuilder request = MockMvcRequestBuilders.get("/v1/user?mobile=13322221111")
- .header("auth","false")
- .param("pageNumber", "")
- .param("pageSize", "");;
- mvc.perform(request)
- .andDo(print())
- .andExpect(status().isOk());
- }
- @Test
- public void getUserById() throws Exception {
- // get一个id为1的user
- RequestBuilder request = MockMvcRequestBuilders.get("/v1/user/1")
- .header("auth","false");
- mvc.perform(request)
- .andDo(print());
- }
- @Test
- public void putUserInfoById() throws Exception {
- // put修改id为1358的user
- RequestBuilder request = MockMvcRequestBuilders.put("/v1/user/1358")
- .header("auth","false")
- .param("updateType","")
- .param("userName", "测试终极大师")
- .param("email", "11111@qq.com");
- mvc.perform(request)
- .andDo(print());
- }
- @Test
- public void delUserInfoById() throws Exception {
- //del删除id为1358的user
- RequestBuilder request = MockMvcRequestBuilders.delete("/v1/user/1358")
- .header("auth","false");
- mvc.perform(request)
- .andDo(print());
- }
- }
SpringBoot 构建RestFul API 含单元测试的更多相关文章
- Spring Boot构建RESTful API与单元测试
如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下相关的内容. @Controller:修饰class,用来创建处理http请求的对象 @RestController:Spr ...
- Spring Boot 2.x基础教程:构建RESTful API与单元测试
首先,回顾并详细说明一下在快速入门中使用的@Controller.@RestController.@RequestMapping注解.如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建 ...
- SpringBoot构建RESTful API
1.RESTful介绍 RESTful是一种软件架构风格! RESTful架构风格规定,数据的元操作,即CRUD(create, read, update和delete,即数据的增删查改)操作,分别对 ...
- springboot集成swagger2构建RESTful API文档
在开发过程中,有时候我们需要不停的测试接口,自测,或者交由测试测试接口,我们需要构建一个文档,都是单独写,太麻烦了,现在使用springboot集成swagger2来构建RESTful API文档,可 ...
- Springboot 如何加密,以及利用Swagger2构建Restful API
先看一下使用Swagger2构建Restful API效果图 超级简单的,只需要在pom 中引用如下jar包 <dependency> <groupId>io.springfo ...
- springmvc/springboot开发restful API
非rest的url写法: 查询 GET /user/query?name=tom 详情 GET /user/getinfo? 创建 POST /user/create?name=tom 修改 POST ...
- 【快学springboot】2.Restful简介,SpringBoot构建Restful接口
Restful简介 Restful一种软件架构风格.设计风格,而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现 ...
- 使用 .NET Core 3.x 构建 RESTFUL Api
准备工作:在此之前你需要了解关于.NET .Core的基础,前面几篇文章已经介绍:https://www.cnblogs.com/hcyesdo/p/12834345.html 首先需要明确一点的就是 ...
- Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档
前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...
随机推荐
- js实现进度条效果
需求分析: 最近学习javascript客户端脚本语言,学到了两个定时器函数setInterval()和setTimeout(),回想起以前在网页上看到的进度条效果可以使用定时器来实现,所以完成了进度 ...
- [转帖]Git数据存储的原理浅析
Git数据存储的原理浅析 https://segmentfault.com/a/1190000016320008 写作背景 进来在闲暇的时间里在看一些关系P2P网络的拓扑发现的内容,重点关注了Ma ...
- Java之HashMap用法
源码: package test_demo; import java.util.HashMap; import java.util.Iterator; import java.util.Map; im ...
- Entity Framework(EF) Code First将实体中的string属性映射成text类型的几种方式
1.通过ColumnType属性设置 [Column(TypeName="text")] public string Text { get; set; } 在进行以上属性设置时,请 ...
- BZOJ5418 NOI2018屠龙勇士(excrt)
显然multiset求出每次用哪把剑.注意到除了p=1的情况,其他数据都保证了ai<pi,于是先特判一下p=1.比较坑的是还可能存在ai=pi,稍微考虑一下. 剩下的部分即解bix≡ai(mod ...
- Educational Codeforces Round 38 (Rated for Div. 2) C
C. Constructing Tests time limit per test 1 second memory limit per test 256 megabytes input standar ...
- bzoj2817[ZJOI2012]波浪
题目链接: http://www.lydsy.com/JudgeOnline/problem.php?id=2817 波浪 [问题描述] 阿米巴和小强是好朋友. 阿米巴和小强在大海旁边看海水的波涛.小 ...
- 【uoj7】 NOI2014—购票
http://uoj.ac/problem/7 (题目链接) 题意 给出一棵有根树,每次从一个节点出发可以买票到达它的一定范围内的祖先.问对于每一个点,到达根的最小花费是多少. Solution 右转 ...
- 结合NTLM中继和Kerberos委派攻击AD
0x00 前言 在上个月我深入演讲了无约束委派之后,本文将讨论一种不同类型的Kerberos委派:基于资源的约束委派.本文的内容基于Elad Shamir的Kerberos研究,并结合我自己的NTLM ...
- 改变 小程序 select 多选框 选中图片
https://www.jianshu.com/p/11eb5b0bfe1a 注意 博客介绍的 在 wxss backgroung-image 中引入小程序内图片是不可的,传到cdn上才实现