mock测试spring boot的CRUD服务

2024-05-13 13:32

本文主要是介绍mock测试spring boot的CRUD服务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

controller如下:

 

 
  1. @RestController

  2. public class GithubController {

  3.     @Autowired

  4.     private GitHubRepository repository;

  5.     

  6.     @Autowired

  7.     private GithubEntityManager manager;

  8.     

  9.     /**

  10.      * attention:用户名可能存在多个

  11.      * Details:根据用户名查询数据库

  12.      * @author chhliu

  13.      */

  14.     @RequestMapping(value="github/get/users/{username}", method=RequestMethod.GET)

  15.     public ResultMsg<List<GitHubEntity>> getGithubByUsername(@PathVariable("username") final String username){

  16.         ResultMsg<List<GitHubEntity>> res = new ResultMsg<List<GitHubEntity>>();

  17.         try {

  18.             Assert.hasLength(username, "username must be not null!");

  19.             List<GitHubEntity> list = repository.findEntityByUserName(username);

  20.             res.setResponseObject(list);

  21.             res.setOK(true);

  22.         } catch (Exception e) {

  23.             res.setErrorMsg(e.getMessage());

  24.             res.setOK(false);

  25.         }

  26.         return res;

  27.     }

  28.     

  29.     /**

  30.      * attention:id唯一

  31.      * Details:根据id查询数据库

  32.      * @author chhliu

  33.      */

  34.     @RequestMapping(value="github/get/user/{id}", method=RequestMethod.GET)

  35.     public ResultMsg<GitHubEntity> getGithubById(@PathVariable("id") final int id){

  36.         ResultMsg<GitHubEntity> msg = new ResultMsg<GitHubEntity>();

  37.         try {

  38.             boolean isExists = repository.exists(id);

  39.             if(isExists){

  40.                 GitHubEntity en = repository.findOne(id);

  41.                 msg.setResponseObject(en);

  42.                 msg.setOK(true);

  43.             }else{

  44.                 msg.setErrorMsg("the record id is not exist!");

  45.                 msg.setOK(false);

  46.             }

  47.         } catch (Exception e) {

  48.             msg.setErrorMsg(e.getMessage());

  49.             msg.setOK(false);

  50.         }

  51.         return msg;

  52.     }

  53.     

  54.     /**

  55.      * attention:

  56.      * Details:查询所有的结果,并分页和排序

  57.      * @author chhliu

  58.      */

  59.     @RequestMapping(value="github/get/users/page", method=RequestMethod.GET)

  60.     public ResultMsg<Page<GitHubEntity>> findAllGithubEntity(final int pageOffset, final int pageSize, final String orderColumn){

  61.         ResultMsg<Page<GitHubEntity>> res = new ResultMsg<Page<GitHubEntity>>();

  62.         try {

  63.             res.setResponseObject(manager.findAllGithubEntity(pageOffset, pageSize, orderColumn));

  64.             res.setOK(true);

  65.         } catch (Exception e) {

  66.             res.setErrorMsg(e.getMessage());

  67.             res.setOK(false);

  68.         }

  69.         return res;

  70.     }

  71.     

  72.     /**

  73.      * attention:

  74.      * Details:插入一个实体到数据库中

  75.      * @author chhliu

  76.      */

  77.     @Modifying

  78.     @RequestMapping(value="github/post" ,method=RequestMethod.POST)

  79.     public ResultMsg<GitHubEntity> saveGithubEntity(@RequestBody final GitHubEntity entity){

  80.         ResultMsg<GitHubEntity> res = new ResultMsg<GitHubEntity>();

  81.         try {

  82.             Assert.notNull(entity, "the insert record must not be null!");

  83.             res.setResponseObject(repository.save(entity));

  84.             res.setOK(true);

  85.         } catch (Exception e) {

  86.             res.setErrorMsg(e.getMessage());

  87.             res.setOK(false);

  88.         }

  89.         return res;

  90.     }

  91.     

  92.     /**

  93.      * attention:

  94.      * Details:更新一个实体类

  95.      * @author chhliu

  96.      */

  97.     @Modifying

  98.     @RequestMapping(value="github/put", method=RequestMethod.PUT)

  99.     public ResultMsg<GitHubEntity> updateGithubEntity(final GitHubEntity entity){

  100.         ResultMsg<GitHubEntity> res = new ResultMsg<GitHubEntity>();

  101.         try {

  102.             Assert.notNull(entity, "the update record must not be null!");

  103.             Assert.notNull(entity.getId(), "the record id must not be null!");

  104.             boolean isExists = repository.exists(entity.getId());

  105.             if(isExists){

  106.                 GitHubEntity en = repository.findOne(entity.getId());

  107.                 if(null != en){

  108.                     en.setCodeSnippet(entity.getCodeSnippet());

  109.                     en.setCodeUrl(entity.getCodeUrl());

  110.                     en.setProjectUrl(entity.getProjectUrl());

  111.                     en.setSensitiveMessage(entity.getSensitiveMessage());

  112.                     en.setSpriderSource(entity.getSpriderSource());

  113.                     en.setSpriderUrl(entity.getSpriderUrl());

  114.                     en.setUserName(entity.getUserName());

  115.                     res.setResponseObject(repository.save(en));

  116.                     res.setOK(true);

  117.                 }else{

  118.                     res.setOK(false);

  119.                     res.setErrorMsg("doesn't find the record by id!");

  120.                 }

  121.             }else{

  122.                 res.setOK(false);

  123.                 res.setErrorMsg("the record id is not exist!");

  124.             }

  125.             

  126.         } catch (Exception e) {

  127.             res.setErrorMsg(e.getMessage());

  128.             res.setOK(false);

  129.         }

  130.         return res;

  131.     }

  132.     

  133.     /**

  134.      * attention:

  135.      * Details:根据id删除一条数据

  136.      * @author chhliu

  137.      */

  138.     @RequestMapping(value="github/delete/{id}", method=RequestMethod.DELETE)

  139.     public ResultMsg<Boolean> deleteGithubEntity(@PathVariable("id") final int id){

  140.         ResultMsg<Boolean> res = new ResultMsg<Boolean>();

  141.         try {

  142.             Assert.notNull(id);

  143.             boolean isExist = repository.exists(id);

  144.             if(isExist){

  145.                 repository.delete(id);

  146.                 res.setOK(true);

  147.                 res.setResponseObject(true);

  148.             }else{

  149.                 res.setOK(false);

  150.                 res.setErrorMsg("the record id is not exist!");

  151.             }

  152.         } catch (Exception e) {

  153.             res.setErrorMsg(e.getMessage());

  154.             res.setOK(false);

  155.         }

  156.         return res;

  157.     }

  158. }

测试代码如下:

 

 

 
  1. @RunWith(SpringJUnit4ClassRunner.class)

  2. @SpringBootTest(classes = CldpApplication.class)

  3. @WebAppConfiguration

  4. public class GitHubControllerTest {

  5. @Autowired

  6. private GithubController controller;

  7.  
  8. private MockMvc mvc;

  9.  
  10. @Before

  11. public void setUp() throws Exception {

  12. mvc = MockMvcBuilders.standaloneSetup(controller).build();

  13. }

  14.  
  15. /**

  16. * attention:

  17. * Details:测试查询

  18. * @author chhliu

  19. * 创建时间:2016-12-7 下午3:41:34

  20. * @throws Exception

  21. * void

  22. */

  23. @Test

  24. public void getGitHubEntityByUsername() throws Exception {

  25. MvcResult result = mvc.perform(

  26. MockMvcRequestBuilders.get("/github/get/users/Datartisan")

  27. .accept(MediaType.APPLICATION_JSON))

  28. .andReturn();

  29. int statusCode = result.getResponse().getStatus();

  30. Assert.assertEquals(statusCode, 200);

  31. String body = result.getResponse().getContentAsString();

  32. System.out.println("body:"+body);

  33. }

  34.  
  35. /**

  36. * attention:

  37. * Details:测试查询

  38. * @author chhliu

  39. * 创建时间:2016-12-7 下午3:41:49

  40. * @throws Exception

  41. * void

  42. */

  43. @Test

  44. public void getGitHubEntityById() throws Exception {

  45. MvcResult result = mvc.perform(

  46. MockMvcRequestBuilders.get("/github/get/user/721")

  47. .accept(MediaType.APPLICATION_JSON))

  48. .andReturn();

  49. int statusCode = result.getResponse().getStatus();

  50. Assert.assertEquals(statusCode, 200);

  51. String body = result.getResponse().getContentAsString();

  52. System.out.println("body:"+body);

  53. }

  54.  
  55. /**

  56. * attention:

  57. * Details:测试分页查询

  58. * @author chhliu

  59. * 创建时间:2016-12-7 下午3:42:02

  60. * @throws Exception

  61. * void

  62. */

  63. @Test

  64. public void getGitHubEntityPage() throws Exception {

  65. MvcResult result = mvc.perform(

  66. MockMvcRequestBuilders.get("/github/get/users/page").param("pageOffset", "0")

  67. .param("pageSize", "10").param("orderColumn", "id").accept(MediaType.APPLICATION_JSON))

  68. .andReturn();

  69. int statusCode = result.getResponse().getStatus();

  70. Assert.assertEquals(statusCode, 200);

  71. String body = result.getResponse().getContentAsString();

  72. System.out.println("body:"+body);

  73. }

  74.  
  75. /**

  76. * attention:

  77. * Details:测试插入,方式一,此方式需要controller中方法参数前没有@RequestBody

  78. * @author chhliu

  79. * 创建时间:2016-12-7 下午3:42:19

  80. * @throws Exception

  81. * void

  82. */

  83. @Test

  84. public void postGithubEntity() throws Exception{

  85. RequestBuilder request = MockMvcRequestBuilders.post("/github/post")

  86. .param("codeSnippet", "package")

  87. .param("codeUrl", "http://localhost:8080/code")

  88. .param("projectUrl", "http://localhost:8080")

  89. .param("userName", "chhliu")

  90. .param("sensitiveMessage", "love")

  91. .param("spriderSource", "CSDN")

  92. .contentType(MediaType.APPLICATION_JSON_UTF8);

  93. MvcResult result = mvc.perform(request)

  94. .andReturn();

  95. int statusCode = result.getResponse().getStatus();

  96. Assert.assertEquals(statusCode, 200);

  97. String body = result.getResponse().getContentAsString();

  98. System.out.println("body:"+body);

  99. }

  100.  
  101. /**

  102. * attention:

  103. * Details:测试插入,方式二,此方式需要controller中方法参数前加@RequestBody

  104. * @author chhliu

  105. * 创建时间:2016-12-7 下午3:42:19

  106. * @throws Exception

  107. * void

  108. */

  109. @Test

  110. public void postGithubEntity1() throws Exception{

  111. GitHubEntity entity = new GitHubEntity();

  112. entity.setUserName("xyhg");

  113. entity.setSpriderSource("ITeye");

  114. entity.setCodeUrl("http://localhost:8080");

  115. ObjectMapper mapper = new ObjectMapper();

  116. MvcResult result = mvc.perform(MockMvcRequestBuilders.post("/github/post")

  117. .contentType(MediaType.APPLICATION_JSON_UTF8)

  118. .content(mapper.writeValueAsString(entity)))

  119. .andExpect(MockMvcResultMatchers.status().isOk())

  120. .andReturn();

  121. int statusCode = result.getResponse().getStatus();

  122. Assert.assertEquals(statusCode, 200);

  123. String body = result.getResponse().getContentAsString();

  124. System.out.println("body:"+body);

  125. }

  126.  
  127. /**

  128. * attention:

  129. * Details:测试更新和插入类似

  130. * @author chhliu

  131. * 创建时间:2016-12-7 下午3:42:32

  132. * @throws Exception

  133. * void

  134. */

  135. @Test

  136. public void putGithubEntity() throws Exception{

  137. RequestBuilder request = MockMvcRequestBuilders.put("/github/put")

  138. .param("id", "719")

  139. .param("codeSnippet", "import java.lang.exception")

  140. .param("codeUrl", "http://localhost:8080/code")

  141. .param("projectUrl", "http://localhost:8080")

  142. .param("userName", "xyh")

  143. .param("sensitiveMessage", "love")

  144. .param("spriderSource", "CSDN");

  145. MvcResult result = mvc.perform(request)

  146. .andReturn();

  147. int statusCode = result.getResponse().getStatus();

  148. Assert.assertEquals(statusCode, 200);

  149. String body = result.getResponse().getContentAsString();

  150. System.out.println("body:"+body);

  151. }

  152.  
  153. @Test

  154. public void deleteGithubEntity() throws Exception{

  155. RequestBuilder request = MockMvcRequestBuilders.delete("/github/delete/719");

  156. MvcResult result = mvc.perform(request)

  157. .andReturn();

  158. int statusCode = result.getResponse().getStatus();

  159. Assert.assertEquals(statusCode, 200);

  160. String body = result.getResponse().getContentAsString();

  161. System.out.println("body:"+body);

  162. }

  163. }

其中@SpringBootTest是@SpringApplicationConfiguration的替代注解,因为后者在spring boot1.4之后就被废弃了。

 

下面来看下这3个注解的作用

@RunWith:引入spring-test测试支持

@SpringBootTest:指定Spring boot工程的Application启动类

@WebAppConfiguration:Spring boot用来模拟ServletContext,并加载上下文

测试过程中,我们需要构建MockMvc,通过该类可以模拟发送,接收Restful请求

测试效果示例如下:

body:{"errorCode":null,"errorMsg":null,"responseObject":{"id":734,"createTime":1481103420245,"spriderSource":"ITeye","spriderUrl":null,"userName":"xyhg","projectUrl":null,"codeUrl":"http://localhost:8080","codeSnippet":null,"sensitiveMessage":null},"ok":true}

可以发现,测试通过了,并且返回结果和在浏览器中输入对应的url返回的结果是一致的!

这篇关于mock测试spring boot的CRUD服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/985840

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Java中的.close()举例详解

《Java中的.close()举例详解》.close()方法只适用于通过window.open()打开的弹出窗口,对于浏览器的主窗口,如果没有得到用户允许是不能关闭的,:本文主要介绍Java中的.... 目录当你遇到以下三种情况时,一定要记得使用 .close():用法作用举例如何判断代码中的 input

Linux创建服务使用systemctl管理详解

《Linux创建服务使用systemctl管理详解》文章指导在Linux中创建systemd服务,设置文件权限为所有者读写、其他只读,重新加载配置,启动服务并检查状态,确保服务正常运行,关键步骤包括权... 目录创建服务 /usr/lib/systemd/system/设置服务文件权限:所有者读写js,其他