• 相关博文:

  • 从消费者角度评估RestFul的意义

    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',
      // 略
      })
    • 获取ID为1 的用户

    • $.ajax({
      url: '../v1/user/1',
      type: 'GET',
      dataType: 'json',
      data: {
      //TODO
      },
      success: function(data) {
      //TODO
      }
      });
    • 更新用户ID为1 的用户信息

      $.ajax({
      url: '../v1/user/1',
      type: 'PUT',
      dataType: 'json',
      data: {
      //TODO new user data
      },
      success: function(data) {
      //TODO
      }
      });
    • 删除用户ID为1的用户

    • $.ajax({
      url: '../v1/user/1',
      type: 'DELETE',
      dataType: 'json',
      data: {
      //TODO other param
      },
      success: function(data) {
      //TODO
      }
      });
  •   测试用例
    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 含单元测试的更多相关文章

  1. Spring Boot构建RESTful API与单元测试

    如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下相关的内容. @Controller:修饰class,用来创建处理http请求的对象 @RestController:Spr ...

  2. Spring Boot 2.x基础教程:构建RESTful API与单元测试

    首先,回顾并详细说明一下在快速入门中使用的@Controller.@RestController.@RequestMapping注解.如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建 ...

  3. SpringBoot构建RESTful API

    1.RESTful介绍 RESTful是一种软件架构风格! RESTful架构风格规定,数据的元操作,即CRUD(create, read, update和delete,即数据的增删查改)操作,分别对 ...

  4. springboot集成swagger2构建RESTful API文档

    在开发过程中,有时候我们需要不停的测试接口,自测,或者交由测试测试接口,我们需要构建一个文档,都是单独写,太麻烦了,现在使用springboot集成swagger2来构建RESTful API文档,可 ...

  5. Springboot 如何加密,以及利用Swagger2构建Restful API

    先看一下使用Swagger2构建Restful API效果图 超级简单的,只需要在pom 中引用如下jar包 <dependency> <groupId>io.springfo ...

  6. springmvc/springboot开发restful API

    非rest的url写法: 查询 GET /user/query?name=tom 详情 GET /user/getinfo? 创建 POST /user/create?name=tom 修改 POST ...

  7. 【快学springboot】2.Restful简介,SpringBoot构建Restful接口

    Restful简介 Restful一种软件架构风格.设计风格,而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现 ...

  8. 使用 .NET Core 3.x 构建 RESTFUL Api

    准备工作:在此之前你需要了解关于.NET .Core的基础,前面几篇文章已经介绍:https://www.cnblogs.com/hcyesdo/p/12834345.html 首先需要明确一点的就是 ...

  9. Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档

    前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...

随机推荐

  1. Daily Scrum - 11/17

    今天小组例会内容较少.拜重阳将一个简易的UI设计好push上TFS了,其他人没有太多进展.在原有项目基础上继续开发看似工作量变少,其实开始需要弄清楚原先代码的实现架构和各种借口还是比较困难的.

  2. PAT 甲级 1029 Median

    https://pintia.cn/problem-sets/994805342720868352/problems/994805466364755968 Given an increasing se ...

  3. Ubuntu忘记MySQL密码重设方法

    ====================忘了mysql密码,从网上找到的解决方案记录在这里==================== 结束当前正在运行的mysql进程 # /etc/init.d/mys ...

  4. Linux kernel 发布 5.0-rc1 版本

    Linux kernel 要发布 5.0 了.. 跟原因是 linus 认为 4.21的小版本号太多了... 邮件内容如下: https://lore.kernel.org/lkml/20190107 ...

  5. [转帖] Windows 与linux的栈大小问题

    一般来说,我们所用的内存有栈和堆之分,其它的我们很少控制,栈的速度快,但是空间小.不灵活:而堆的空间几乎可以满足任何要求.灵活,但是相对的速度要慢了很多,并且在VC中堆是人为控制的,new了就要del ...

  6. 伪数组(arguments及字符串)转数组的方法 贼简单

    超简单的伪数组转数组的方法, 简单到令人发指! (这里伪数组使用arguments) 1.使用 Array.prototype.slice Array.prototype.slice.call(arg ...

  7. CF10D LCIS

    题意翻译 求两个串的最长公共上升子序列. 题目描述 This problem differs from one which was on the online contest. The sequenc ...

  8. Cheerleaders UVA - 11806(容斥+二进制技巧)

    #include <iostream> #include <cstdio> #include <sstream> #include <cstring> ...

  9. MT【181】横穿四象限

    设函数$f(x)=\dfrac{1}{x-a}-\dfrac{\lambda}{x-2}$,其中$a,\lambda\in R$记$A_1=\{(x,y)|x>0,y>0\},A_2=\{ ...

  10. windows下非管理员权限安装mysql

    windows下,mysql有两种安装方式: 1.msi安装 2.zip安装 无论是哪种安装方式,都因为需要将mysql安装为一个服务,所以必须要以管理员权限安装. 因为公司的换了虚拟机,无法取得管理 ...