欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mock测试spring boot的CRUD服务

程序员文章站 2022-04-23 15:56:28
...

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返回的结果是一致的!