Spring Boot 单元测试(IDEA自动生成测试类、MockMvc)
一、IDEA自动生成测试类
1.安装插件JUnitGenerator V2.0
File---->Settings---->Browse Repositories
2.安装好后把JUnit和JUnitGenerator V2.0一起勾上
3.配置插件
把package上test.前缀去掉
配置测试类生成的地址
${SOURCEPATH}/../../test/java/${PACKAGE}/${FILENAME}
4.对着要生成的类
4.对着要生成的类
二、测试service类
- package com.sid.service.impl;
- import com.sid.service.UserService;
- import org.junit.After;
- import org.junit.Assert;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import static org.hamcrest.CoreMatchers.*;
- import static org.junit.Assert.*;
- /**
- * @Description: Service层单元测试 启动了服务
- * @Param:
- * @return:
- * @Author: Sid
- * @Date: 2018-10-24 13:53
- * @since: 1.0
- */
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class UserServiceImplTest {
- /**
- * @Description: 直接测试service 用IOC注入进来 这样run的时候会先启动springboot项目
- * @Param:
- * @return:
- * @Author: Sid
- * @Date: 2018-10-24 13:42
- * @since: 1.0
- */
- @Autowired
- UserService userService;
- @Before
- public void setUp() throws Exception {
- }
- @After
- public void tearDown() throws Exception {
- }
- @Test
- public void set() {
- userService.set("sid:test:string:key:","lalala");
- String value = userService.get("sid:test:string:key:");
- Assert.assertEquals("lalala",value);
- //可以只使用 assertThat 一个断言语句,结合 Hamcrest 提供的匹配符,就可以表达全部的测试思想
- //引入import static org.hamcrest.CoreMatchers.*;
- Assert.assertThat(value,is("lalala"));
- }
- }
三、测试Controller类
有两种方法,1可以跟上面一样用@Autowired把Controller注入进来然后调用Controller的方法。参照上方,这里不介绍。
2.用MockMvc模拟完整的HTTP请求
- package com.sid.controller;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.http.MediaType;
- import org.springframework.test.context.junit4.SpringRunner;
- import org.springframework.test.web.servlet.MockMvc;
- import org.springframework.test.web.servlet.MvcResult;
- import org.springframework.test.web.servlet.ResultActions;
- import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
- import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
- import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
- import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
- import org.springframework.test.web.servlet.setup.MockMvcBuilders;
- import org.springframework.web.context.WebApplicationContext;
- import static org.hamcrest.CoreMatchers.*;
- import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
- /**
- * @Description: Controller层单元测试 注入Spring 上下文的环境到 MockMvc 中 测试时会启动项目
- * @Param:
- * @return:
- * @Author: Sid
- * @Date: 2018-10-24 13:45
- * @since: 1.0
- */
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class UserControllerTest {
- /**
- * @Description: 使用MockMvc 模拟HTTP请求 来测试controller
- * MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,
- * 这样可以使得测试速度快、不依赖网络环境,而且提供了一套验证的工具,这样可以使得请求的验证统一而且很方便。
- *
- * // 模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。
- * @Param:
- * @return:
- * @Author: Sid
- * @Date: 2018-10-24 13:43
- * @since: 1.0
- */
- private MockMvc mvc;
- @Autowired
- private WebApplicationContext wac; // 注入WebApplicationContext
- /**
- * @Description: 直接注入userController 然后调用userController的方法来测试
- * @Param:
- * @return:
- * @Author: Sid
- * @Date: 2018-10-24 13:44
- * @since: 1.0
- */
- // @Autowired
- // private UserController userController;
- @Before
- public void setUp() throws Exception {
- //使用 WebApplicationContext 构建 MockMvc
- this.mvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
- }
- @After
- public void tearDown() throws Exception {
- }
- @Test
- public void addUser() throws Exception {
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/add")
- .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
- //form表单格式传参
- .param("id", "4")
- .param("name", "junit test")
- .param("password", "111")
- .param("mobilePhone", "18523980000")
- .characterEncoding("utf-8")
- .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
- ResultActions result = mvc.perform(requestBuilder);
- MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
- .andDo(MockMvcResultHandlers.print())
- .andReturn();// 返回执行请求的结果
- System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
- }
- @Test
- public void deleteUser() throws Exception {
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/delete")
- .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
- //form表单格式传参
- .param("mobilePhone", "18523980000")
- .characterEncoding("utf-8")
- .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
- ResultActions result = mvc.perform(requestBuilder);
- MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
- .andExpect(MockMvcResultMatchers.jsonPath("$").value(1))
- .andDo(MockMvcResultHandlers.print())
- .andReturn();// 返回执行请求的结果
- System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
- }
- @Test
- public void updateUser() throws Exception {
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/update")
- .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
- //form表单格式传参
- .param("id", "1")
- .param("name", "李沂桀")
- .param("mobilePhone", "185")
- .param("password", "5")
- .characterEncoding("utf-8")
- .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
- ResultActions result = mvc.perform(requestBuilder);
- MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
- .andDo(MockMvcResultHandlers.print())
- .andReturn();// 返回执行请求的结果
- System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
- }
- @Test
- public void selectAll() throws Exception {
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/selectAll")
- .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
- //form表单格式传参
- .param("pageNum", "1")
- .param("pageSize", "5")
- .characterEncoding("utf-8")
- .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
- ResultActions result = mvc.perform(requestBuilder);
- MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
- .andExpect(jsonPath("list").exists())
- .andExpect(jsonPath("$.list", notNullValue()))
- .andExpect(jsonPath("$.list[0].id", is(1)))
- .andDo(MockMvcResultHandlers.print())
- .andReturn();// 返回执行请求的结果
- System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
- }
- @Test
- public void getUserByMobilePhone() throws Exception {
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/getUserByMobilePhone")
- .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
- //form表单格式传参
- .param("mobilePhone", "18523980000")
- .characterEncoding("utf-8")
- .accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
- ResultActions result = mvc.perform(requestBuilder);
- MvcResult mvcResult = result.andExpect(MockMvcResultMatchers.status().isOk())
- .andExpect(jsonPath("$", notNullValue()))
- .andExpect(jsonPath("$.name", is("junit test")))
- .andDo(MockMvcResultHandlers.print())
- .andReturn();// 返回执行请求的结果
- System.out.println("response------------------:"+mvcResult.getResponse().getContentAsString());
- }
- @Test
- public void set() {
- }
- @Test
- public void get() {
- }
- }