• 相关博文:

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

    SpringBoot 构建RestFul API 含单元测试

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

    • @Controller :修饰class,用来创建处理http请求的对象
    • @RestController :Spring4之后加入的注解,原来在  @Controller 中返回json需要  @ResponseBody 来配合,如果直接用  @RestController 替代  @Controller 就不需要再配置  @ResponseBody ,默认返回json格式。
    • @RequestMapping :配置url映射
  • Controller 层
  1. package com.creditease.bsettle.crm.controller.user;
  2.  
  3. import com.creditease.bsettle.crm.model.User;
  4. import com.creditease.bsettle.crm.service.UserService;
  5. import com.creditease.bsettle.crm.util.ResponseUtil;
  6. import com.creditease.bsettle.monitor.base.controller.BaseCommonQueryController;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.web.bind.annotation.*;
  10.  
  11. import javax.servlet.http.HttpServletRequest;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14.  
  15. @Slf4j
  16. @RequestMapping(value = "/v1/users")
  17. @RestController
  18. public class UserControllerRestFulDemo extends BaseCommonQueryController<User>{
  19.  
  20. @Autowired
  21. UserService userService;
  22.  
  23. @RequestMapping(value = "",method = RequestMethod.GET)
  24. @ResponseBody
  25. public Map<String, Object> pageList(HttpServletRequest request, @RequestParam Map<String, String> searchParams) {
  26. Map<String, Object> maps = new HashMap<String, Object>();
  27. try {
  28. //TODO do something
  29. //maps = userService.queryPage(searchParams);
  30. } catch (Exception var4) {
  31. log.error(var4.getMessage(), var4);
  32. maps.put("retCode", Boolean.valueOf(false));
  33. maps.put("retMessage", var4.getMessage());
  34. }
  35.  
  36. return maps;
  37. }
  38.  
  39. /**
  40. * 根据用户ID 查询用户信息
  41. * @param request
  42. * @param id
  43. * @return
  44. */
  45. @RequestMapping(value = "/{id}",method = RequestMethod.GET)
  46. @ResponseBody
  47. Map<String,Object> findUser(HttpServletRequest request,@PathVariable Long id) {
  48. Map<String,Object> resultMap = ResponseUtil.createMap(true,"操作成功!");
  49. try {
  50. //TODO do something
  51. /* User user = userService.findUserById(id);
  52. resultMap.put("user",user);*/
  53. }catch(Exception e){
  54. log.error("findUserById is Exception !!! {} \n",e);
  55. resultMap = ResponseUtil.createMap(false,"操作失败!"+e.getMessage());
  56. }
  57. return resultMap;
  58. }
  59.  
  60. /**
  61. * 修改用户信息
  62. * @param request
  63. * @param user
  64. * @param updateType 修改类型 1:修改密码 2:修改用户信息 3:修改用户状态
  65. * @return
  66. */
  67. @RequestMapping(value="/{id}", method = RequestMethod.PUT)
  68. @ResponseBody
  69. Map<String,Object> updateUserInfo(HttpServletRequest request,@ModelAttribute User user,@PathVariable Long id,
  70. @RequestParam("updateType") int updateType){
  71. Map<String,Object> resultMap = ResponseUtil.createMap(true,"操作成功!");
  72. try{
  73. //TODO do something
  74. // userService.updateUser(user,updateType,id);
  75. }catch (Exception e){
  76. log.error("updateUserInfo is Exception !!! {} \n",e);
  77. resultMap = ResponseUtil.createMap(false,"操作失败!"+e.getMessage());
  78. }
  79. return resultMap;
  80. }
  81.  
  82. /**
  83. * 根据用户ID删除用户
  84. * @param request
  85. * @param id
  86. * @return
  87. */
  88. @RequestMapping(value="/{id}", method = RequestMethod.DELETE)
  89. @ResponseBody
  90. Map<String,Object> delUserById(HttpServletRequest request,@PathVariable Long id){
  91. Map<String,Object> resultMap = ResponseUtil.createMap(true,"操作成功!");
  92. try{
  93. //TODO do something
  94. //userService.delete(id);
  95. }catch (Exception e){
  96. log.error("delUserById is Exception !!! {} \n",e);
  97. resultMap = ResponseUtil.createMap(false,"操作失败!"+e.getMessage());
  98. }
  99. return resultMap;
  100. }
  101. /**
  102. * 保存用户信息
  103. * @param request
  104. * @param user
  105. * @return
  106. */
  107. @RequestMapping(value = "", method = RequestMethod.POST)
  108. @ResponseBody
  109. Map<String,Object> saveUserInfo(HttpServletRequest request, @ModelAttribute User user){
  110. Map<String,Object> resultMap = ResponseUtil.createMap(true,"操作成功!");
  111. try{
  112. //TODO do something
  113. //userService.save(user);
  114. }catch (Exception e){
  115. log.error("saveUserInfo is Exception !!! {} \n",e);
  116. resultMap = ResponseUtil.createMap(false,"操作失败!"+e.getMessage());
  117. }
  118. return resultMap;
  119. }
  120. }
  •   View 层
    •    根据查询条件获取user列表

      1. $.ajax({
      2. url: '../v1/users',
      3. async: false,
      4. type: 'GET',
      5. dataType: 'json
      6. data: {
      7. //TODO
      8. } ,
      9. success: function(data) {
      10. //TODO
      11. }
      12. });

      OR

      1. $('#userTable').bootstrapTable({
      2. method: 'GET',
      3. url: '../v1/user',
      4. dataType: 'json',
      5. pagination: true,
      6. pageList: [,,,],
      7. pageNumber: ,
      8. pageSize: ,
      9. //singleSelect: true,
      10. clickToSelect: true,
      11. sidePagination: 'server',
      12. queryParams: queryParams,
      13. locale: 'zh-CN',
      14. // 略
      15. })
    • 获取ID为1 的用户

      1. $.ajax({
      2. url: '../v1/user/1',
      3. type: 'GET',
      4. dataType: 'json',
      5. data: {
      6. //TODO
      7. },
      8. success: function(data) {
      9. //TODO
      10. }
      11. });
    • 更新用户ID为1 的用户信息

      1. $.ajax({
      2. url: '../v1/user/1',
      3. type: 'PUT',
      4. dataType: 'json',
      5. data: {
      6. //TODO new user data
      7. },
      8. success: function(data) {
      9. //TODO
      10. }
      11. });
    • 删除用户ID为1的用户

      1. $.ajax({
      2. url: '../v1/user/1',
      3. type: 'DELETE',
      4. dataType: 'json',
      5. data: {
      6. //TODO other param
      7. },
      8. success: function(data) {
      9. //TODO
      10. }
      11. });
  •   测试用例
    1. package com.creditease.bsettle.crm;
    2.  
    3. import org.junit.Before;
    4. import org.junit.Test;
    5. import org.junit.runner.RunWith;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.boot.test.context.SpringBootTest;
    8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    9. import org.springframework.test.context.web.WebAppConfiguration;
    10. import org.springframework.test.web.servlet.MockMvc;
    11. import org.springframework.test.web.servlet.RequestBuilder;
    12. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    13. import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    14. import org.springframework.web.context.WebApplicationContext;
    15.  
    16. import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
    17. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    18. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    19.  
    20. /**
    21. * @author mengfanzhu
    22. * @Package com.creditease.bsettle.crm
    23. * @Description:
    24. * @date 5/19/17 10:40
    25. * */
    26. @RunWith(SpringJUnit4ClassRunner.class)
    27. @SpringBootTest(classes = CrmApplication.class)
    28. @WebAppConfiguration
    29. public class UserServiceRestTest {
    30.  
    31. @Autowired
    32. private WebApplicationContext wac;
    33. private MockMvc mvc;
    34.  
    35. @Before
    36. public void setUp() throws Exception {
    37. // mvc = MockMvcBuilders.standaloneSetup(new UserControllerRestFulDemo()).build();
    38. mvc = MockMvcBuilders.webAppContextSetup(wac).build();
    39. }
    40.  
    41. @Test
    42. public void getUserList() throws Exception {
    43. // 1、get查一下user列表
    44. RequestBuilder request = MockMvcRequestBuilders.get("/v1/users")
    45. .header("auth", "false")
    46. .param("pageNumber", "")
    47. .param("pageSize", "");
    48. mvc.perform(request)
    49. .andDo(print()) //print request and response to Console
    50. .andExpect(status().isOk())
    51. .andExpect(content().contentType("application/json;charset=UTF-8"));
    52. }
    53.  
    54. @Test
    55. public void postUser() throws Exception {
    56. // 2、post提交一个userRequestBuilder
    57. RequestBuilder request = MockMvcRequestBuilders.post("/v1/user")
    58. .header("auth","false")
    59. .param("isModifyPassword","N")
    60. .param("status","O")
    61. .param("userName","testName"+System.currentTimeMillis())
    62. .param("userLoginPassword","aaaa1234")
    63. .param("mobile","")
    64. .param("email","fjksdfj@11.com")
    65. .param("crmEnterpriseId","");
    66. mvc.perform(request)
    67. .andDo(print());
    68.  
    69. }
    70.  
    71. @Test
    72. public void getUser() throws Exception {
    73. // get获取user列表,应该有刚才插入的数据
    74. RequestBuilder request = MockMvcRequestBuilders.get("/v1/user?mobile=13322221111")
    75. .header("auth","false")
    76. .param("pageNumber", "")
    77. .param("pageSize", "");;
    78. mvc.perform(request)
    79. .andDo(print())
    80. .andExpect(status().isOk());
    81. }
    82.  
    83. @Test
    84. public void getUserById() throws Exception {
    85. // get一个id为1的user
    86. RequestBuilder request = MockMvcRequestBuilders.get("/v1/user/1")
    87. .header("auth","false");
    88. mvc.perform(request)
    89. .andDo(print());
    90. }
    91.  
    92. @Test
    93. public void putUserInfoById() throws Exception {
    94. // put修改id为1358的user
    95. RequestBuilder request = MockMvcRequestBuilders.put("/v1/user/1358")
    96. .header("auth","false")
    97. .param("updateType","")
    98. .param("userName", "测试终极大师")
    99. .param("email", "11111@qq.com");
    100. mvc.perform(request)
    101. .andDo(print());
    102.  
    103. }
    104.  
    105. @Test
    106. public void delUserInfoById() throws Exception {
    107. //del删除id为1358的user
    108. RequestBuilder request = MockMvcRequestBuilders.delete("/v1/user/1358")
    109. .header("auth","false");
    110. mvc.perform(request)
    111. .andDo(print());
    112.  
    113. }
    114. }

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. js实现进度条效果

    需求分析: 最近学习javascript客户端脚本语言,学到了两个定时器函数setInterval()和setTimeout(),回想起以前在网页上看到的进度条效果可以使用定时器来实现,所以完成了进度 ...

  2. [转帖]Git数据存储的原理浅析

    Git数据存储的原理浅析 https://segmentfault.com/a/1190000016320008   写作背景 进来在闲暇的时间里在看一些关系P2P网络的拓扑发现的内容,重点关注了Ma ...

  3. Java之HashMap用法

    源码: package test_demo; import java.util.HashMap; import java.util.Iterator; import java.util.Map; im ...

  4. Entity Framework(EF) Code First将实体中的string属性映射成text类型的几种方式

    1.通过ColumnType属性设置 [Column(TypeName="text")] public string Text { get; set; } 在进行以上属性设置时,请 ...

  5. BZOJ5418 NOI2018屠龙勇士(excrt)

    显然multiset求出每次用哪把剑.注意到除了p=1的情况,其他数据都保证了ai<pi,于是先特判一下p=1.比较坑的是还可能存在ai=pi,稍微考虑一下. 剩下的部分即解bix≡ai(mod ...

  6. 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 ...

  7. bzoj2817[ZJOI2012]波浪

    题目链接: http://www.lydsy.com/JudgeOnline/problem.php?id=2817 波浪 [问题描述] 阿米巴和小强是好朋友. 阿米巴和小强在大海旁边看海水的波涛.小 ...

  8. 【uoj7】 NOI2014—购票

    http://uoj.ac/problem/7 (题目链接) 题意 给出一棵有根树,每次从一个节点出发可以买票到达它的一定范围内的祖先.问对于每一个点,到达根的最小花费是多少. Solution 右转 ...

  9. 结合NTLM中继和Kerberos委派攻击AD

    0x00 前言 在上个月我深入演讲了无约束委派之后,本文将讨论一种不同类型的Kerberos委派:基于资源的约束委派.本文的内容基于Elad Shamir的Kerberos研究,并结合我自己的NTLM ...

  10. 改变 小程序 select 多选框 选中图片

    https://www.jianshu.com/p/11eb5b0bfe1a 注意 博客介绍的  在 wxss  backgroung-image 中引入小程序内图片是不可的,传到cdn上才实现