springBoot单元测试

Spring Boot 单元测试(IDEA自动生成测试类、MockMvc

一、IDEA自动生成测试类

1.安装插件JUnitGenerator V2.0

File---->Settings---->Browse Repositories

springBoot单元测试_第1张图片

 

2.安装好后把JUnitJUnitGenerator V2.0一起勾上

springBoot单元测试_第2张图片

 

3.配置插件

packagetest.前缀去掉

springBoot单元测试_第3张图片

 

配置测试类生成的地址

${SOURCEPATH}/../../test/java/${PACKAGE}/${FILENAME}

springBoot单元测试_第4张图片

 

4.对着要生成的类

springBoot单元测试_第5张图片

 

4.对着要生成的类

springBoot单元测试_第6张图片

springBoot单元测试_第7张图片

springBoot单元测试_第8张图片

 

 

 

二、测试service

  1. package com.sid.service.impl;
  2.  
  3. import com.sid.service.UserService;
  4. import org.junit.After;
  5. import org.junit.Assert;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. import org.junit.runner.RunWith;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.boot.test.context.SpringBootTest;
  11. import org.springframework.test.context.junit4.SpringRunner;
  12. import static org.hamcrest.CoreMatchers.*;
  13.  
  14. import static org.junit.Assert.*;
  15.  
  16. /**
  17. * @Description: Service层单元测试  启动了服务
  18. * @Param:  
  19. * @return:  
  20. * @Author: Sid
  21. * @Date: 2018-10-24 13:53
  22. * @since: 1.0
  23. */
  24. @RunWith(SpringRunner.class)
  25. @SpringBootTest
  26. public class UserServiceImplTest {
  27.     
  28.     
  29.     /**
  30.     * @Description: 直接测试service  IOC注入进来  这样run的时候会先启动springboot项目
  31.     * @Param:  
  32.     * @return:  
  33.     * @Author: Sid
  34.     * @Date: 2018-10-24 13:42
  35.     * @since: 1.0
  36.     */
  37.     @Autowired
  38.     UserService userService;
  39.  
  40.     @Before
  41.     public void setUp() throws Exception {
  42.     }
  43.  
  44.     @After
  45.     public void tearDown() throws Exception {
  46.     }
  47.  
  48.     @Test
  49.     public void set() {
  50.         userService.set("sid:test:string:key:","lalala");
  51.         String value = userService.get("sid:test:string:key:");
  52.         Assert.assertEquals("lalala",value);
  53.         //可以只使用 assertThat 一个断言语句,结合 Hamcrest 提供的匹配符,就可以表达全部的测试思想
  54.         //引入import static org.hamcrest.CoreMatchers.*;
  55.         Assert.assertThat(value,is("lalala"));
  56.     }
  57.  
  58. }

三、测试Controller

有两种方法,1可以跟上面一样用@AutowiredController注入进来然后调用Controller的方法。参照上方,这里不介绍。

2.MockMvc模拟完整的HTTP请求

  1. package com.sid.controller;
  2.  
  3. import org.junit.After;
  4. import org.junit.Before;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.http.MediaType;
  10. import org.springframework.test.context.junit4.SpringRunner;
  11. import org.springframework.test.web.servlet.MockMvc;
  12. import org.springframework.test.web.servlet.MvcResult;
  13. import org.springframework.test.web.servlet.ResultActions;
  14. import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
  15. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  16. import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
  17. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  18. import org.springframework.test.web.servlet.setup.MockMvcBuilders;
  19. import org.springframework.web.context.WebApplicationContext;
  20. import static org.hamcrest.CoreMatchers.*;
  21. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
  22.  
  23.  
  24. /**
  25. * @Description: Controller层单元测试 注入Spring 上下文的环境到 MockMvc   测试时会启动项目
  26. * @Param:  
  27. * @return:  
  28. * @Author: Sid
  29. * @Date: 2018-10-24 13:45
  30. * @since: 1.0
  31. */
  32. @RunWith(SpringRunner.class)
  33. @SpringBootTest
  34. public class UserControllerTest {
  35.  
  36.     /**
  37.     * @Description: 使用MockMvc 模拟HTTP请求 来测试controller
  38.      * MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,
  39.      * 这样可以使得测试速度快、不依赖网络环境,而且提供了一套验证的工具,这样可以使得请求的验证统一而且很方便。
  40.      *
  41.      * // 模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。
  42.     * @Param:  
  43.     * @return:  
  44.     * @Author: Sid
  45.     * @Date: 2018-10-24 13:43
  46.     * @since: 1.0
  47.     */
  48.  
  49.     private MockMvc mvc;
  50.  
  51.     @Autowired
  52.     private WebApplicationContext wac; // 注入WebApplicationContext
  53.  
  54.     /**
  55.     * @Description: 直接注入userController 然后调用userController的方法来测试
  56.     * @Param:  
  57.     * @return:  
  58.     * @Author: Sid
  59.     * @Date: 2018-10-24 13:44
  60.     * @since: 1.0
  61.     */
  62. //    @Autowired
  63. //    private UserController userController;
  64.  
  65.     @Before
  66.     public void setUp() throws Exception {
  67.         //使用 WebApplicationContext 构建 MockMvc
  68.         this.mvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
  69.     }
  70.  
  71.     @After
  72.     public void tearDown() throws Exception {
  73.     }
  74.  
  75.     @Test
  76.     public void addUser() throws Exception {
  77.         MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/add")
  78.                 .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  79.                 //form表单格式传参
  80.                 .param("id", "4")
  81.                 .param("name", "junit test")
  82.                 .param("password", "111")
  83.                 .param("mobilePhone", "18523980000")
  84.                 .characterEncoding("utf-8")
  85.                 .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
  86.  
  87.         ResultActions result = mvc.perform(requestBuilder);
  88.  
  89.         MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
  90.                 .andDo(MockMvcResultHandlers.print())
  91.                 .andReturn();// 返回执行请求的结果
  92.  
  93.         System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
  94.     }
  95.  
  96.     @Test
  97.     public void deleteUser() throws Exception {
  98.         MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/delete")
  99.                 .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  100.                 //form表单格式传参
  101.                 .param("mobilePhone", "18523980000")
  102.                 .characterEncoding("utf-8")
  103.                 .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
  104.  
  105.         ResultActions result = mvc.perform(requestBuilder);
  106.  
  107.         MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
  108.                 .andExpect(MockMvcResultMatchers.jsonPath("$").value(1))
  109.                 .andDo(MockMvcResultHandlers.print())
  110.                 .andReturn();// 返回执行请求的结果
  111.  
  112.         System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
  113.     }
  114.  
  115.     @Test
  116.     public void updateUser() throws Exception {
  117.         MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/update")
  118.                 .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  119.                 //form表单格式传参
  120.                 .param("id", "1")
  121.                 .param("name", "李沂桀")
  122.                 .param("mobilePhone", "185")
  123.                 .param("password", "5")
  124.                 .characterEncoding("utf-8")
  125.                 .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
  126.  
  127.         ResultActions result = mvc.perform(requestBuilder);
  128.  
  129.         MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
  130.                 .andDo(MockMvcResultHandlers.print())
  131.                 .andReturn();// 返回执行请求的结果
  132.  
  133.         System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
  134.     }
  135.  
  136.     @Test
  137.     public void selectAll() throws Exception {
  138.  
  139.         MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/selectAll")
  140.                 .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  141.                 //form表单格式传参
  142.                 .param("pageNum", "1")
  143.                 .param("pageSize", "5")
  144.                 .characterEncoding("utf-8")
  145.                 .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
  146.  
  147.         ResultActions result = mvc.perform(requestBuilder);
  148.  
  149.         MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
  150.                 .andExpect(jsonPath("list").exists())
  151.                 .andExpect(jsonPath("$.list", notNullValue()))
  152.                 .andExpect(jsonPath("$.list[0].id", is(1)))
  153.                 .andDo(MockMvcResultHandlers.print())
  154.                 .andReturn();// 返回执行请求的结果
  155.  
  156.         System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
  157.  
  158.  
  159.     }
  160.  
  161.     @Test
  162.     public void getUserByMobilePhone() throws Exception {
  163.  
  164.         MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/getUserByMobilePhone")
  165.                 .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  166.                 //form表单格式传参
  167.                 .param("mobilePhone", "18523980000")
  168.                 .characterEncoding("utf-8")
  169.                 .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
  170.  
  171.         ResultActions result = mvc.perform(requestBuilder);
  172.  
  173.         MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
  174.                 .andExpect(jsonPath("$", notNullValue()))
  175.                 .andExpect(jsonPath("$.name", is("junit test")))
  176.                 .andDo(MockMvcResultHandlers.print())
  177.                 .andReturn();// 返回执行请求的结果
  178.  
  179.         System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
  180.  
  181.  
  182.     }
  183.  
  184.  
  185.     @Test
  186.     public void set() {
  187.     }
  188.  
  189.     @Test
  190.     public void get() {
  191.     }
  192. }

 

 

 

你可能感兴趣的:(springBoot单元测试)