SpringBoot项目的一个功能开发完成之后,需要对功能做单元测试,需要项目有单元测试的功能,这个项目是一个新建的项目,所以需要自己弄,下面记载一下步骤。
首先,我们使用点击需要做单元测试的类名,右击使用idea自带生成单元测试文件的功能:
1.点击文件 -> GO TO -> Test
2.
3.
4.生成测试文件
5.加单元测试注解
6.在测试类中添加测试逻辑并运行
Spring Boot Junit 测试Controller
Controller:
[java] view plain copy print?
- package com.xiaolyuh.controller;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.domain.Page;
- import org.springframework.data.domain.PageRequest;
- import org.springframework.data.domain.Sort;
- import org.springframework.data.domain.Sort.Direction;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
- import com.xiaolyuh.entity.Person;
- import com.xiaolyuh.repository.PersonRepository;
- @RestController
- public class DataController {
- // 1 Spring Data JPA已自动为你注册bean,所以可自动注入
- @Autowired
- PersonRepository personRepository;
- /**
- * 保存 save支持批量保存:<S extends T> Iterable<S> save(Iterable<S> entities);
- *
- * 删除: 支持使用id删除对象、批量删除以及删除全部: void delete(ID id); void delete(T entity);
- * void delete(Iterable<? extends T> entities); void deleteAll();
- *
- */
- @RequestMapping("/save")
- public Person save(@RequestBody Person person) {
- Person p = personRepository.save(person);
- return p;
- }
- /**
- * 测试findByAddress
- */
- @RequestMapping("/q1")
- public List<Person> q1(String address) {
- List<Person> people = personRepository.findByAddress(address);
- return people;
- }
- /**
- * 测试findByNameAndAddress
- */
- @RequestMapping("/q2")
- public Person q2(String name, String address) {
- Person people = personRepository.findByNameAndAddress(name, address);
- return people;
- }
- /**
- * 测试withNameAndAddressQuery
- */
- @RequestMapping("/q3")
- public Person q3(String name, String address) {
- Person p = personRepository.withNameAndAddressQuery(name, address);
- return p;
- }
- /**
- * 测试withNameAndAddressNamedQuery
- */
- @RequestMapping("/q4")
- public Person q4(String name, String address) {
- Person p = personRepository.withNameAndAddressNamedQuery(name, address);
- return p;
- }
- /**
- * 测试排序
- */
- @RequestMapping("/sort")
- public List<Person> sort() {
- List<Person> people = personRepository.findAll(new Sort(Direction.ASC, "age"));
- return people;
- }
- /**
- * 测试分页
- */
- @RequestMapping("/page")
- public Page<Person> page(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) {
- Page<Person> pagePeople = personRepository.findAll(new PageRequest(pageNo, pageSize));
- return pagePeople;
- }
- }
package com.xiaolyuh.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.xiaolyuh.entity.Person;
import com.xiaolyuh.repository.PersonRepository;
@RestController
public class DataController {
// 1 Spring Data JPA已自动为你注册bean,所以可自动注入
@Autowired
PersonRepository personRepository;
/**
* 保存 save支持批量保存:<S extends T> Iterable<S> save(Iterable<S> entities);
*
* 删除: 支持使用id删除对象、批量删除以及删除全部: void delete(ID id); void delete(T entity);
* void delete(Iterable<? extends T> entities); void deleteAll();
*
*/
@RequestMapping("/save")
public Person save(@RequestBody Person person) {
Person p = personRepository.save(person);
return p;
}
/**
* 测试findByAddress
*/
@RequestMapping("/q1")
public List<Person> q1(String address) {
List<Person> people = personRepository.findByAddress(address);
return people;
}
/**
* 测试findByNameAndAddress
*/
@RequestMapping("/q2")
public Person q2(String name, String address) {
Person people = personRepository.findByNameAndAddress(name, address);
return people;
}
/**
* 测试withNameAndAddressQuery
*/
@RequestMapping("/q3")
public Person q3(String name, String address) {
Person p = personRepository.withNameAndAddressQuery(name, address);
return p;
}
/**
* 测试withNameAndAddressNamedQuery
*/
@RequestMapping("/q4")
public Person q4(String name, String address) {
Person p = personRepository.withNameAndAddressNamedQuery(name, address);
return p;
}
/**
* 测试排序
*/
@RequestMapping("/sort")
public List<Person> sort() {
List<Person> people = personRepository.findAll(new Sort(Direction.ASC, "age"));
return people;
}
/**
* 测试分页
*/
@RequestMapping("/page")
public Page<Person> page(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) {
Page<Person> pagePeople = personRepository.findAll(new PageRequest(pageNo, pageSize));
return pagePeople;
}
}
测试类:
[java] view plain copy print?
- package com.xiaolyuh;
- import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
- import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
- import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
- import java.util.HashMap;
- import java.util.Map;
- 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.setup.MockMvcBuilders;
- import org.springframework.web.context.WebApplicationContext;
- import net.minidev.json.JSONObject;
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class SpringBootStudentDataJpaApplicationTests {
- @Test
- public void contextLoads() {
- }
- private MockMvc mockMvc; // 模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。
- @Autowired
- private WebApplicationContext wac; // 注入WebApplicationContext
- // @Autowired
- // private MockHttpSession session;// 注入模拟的http session
- //
- // @Autowired
- // private MockHttpServletRequest request;// 注入模拟的http request\
- @Before // 在测试开始前初始化工作
- public void setup() {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
- }
- @Test
- public void testQ1() throws Exception {
- Map<String, Object> map = new HashMap<>();
- map.put("address", "合肥");
- MvcResult result = mockMvc.perform(post("/q1?address=合肥").content(JSONObject.toJSONString(map)))
- .andExpect(status().isOk())// 模拟向testRest发送get请求
- .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
- .andReturn();// 返回执行请求的结果
- System.out.println(result.getResponse().getContentAsString());
- }
- @Test
- public void testSave() throws Exception {
- Map<String, Object> map = new HashMap<>();
- map.put("address", "合肥");
- map.put("name", "测试");
- map.put("age", 50);
- MvcResult result = mockMvc.perform(post("/save").contentType(MediaType.APPLICATION_JSON).content(JSONObject.toJSONString(map)))
- .andExpect(status().isOk())// 模拟向testRest发送get请求
- .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
- .andReturn();// 返回执行请求的结果
- System.out.println(result.getResponse().getContentAsString());
- }
- @Test
- public void testPage() throws Exception {
- MvcResult result = mockMvc.perform(post("/page").param("pageNo", "1").param("pageSize", "2"))
- .andExpect(status().isOk())// 模拟向testRest发送get请求
- .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
- .andReturn();// 返回执行请求的结果
- System.out.println(result.getResponse().getContentAsString());
- }
- }
转载:
https://blog.csdn.net/qq_33206732/article/details/79242107
https://blog.csdn.net/xiaolyuh123/article/details/73281522