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实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.