idea 的SpringBoot项目做单元测试



SpringBoot项目的一个功能开发完成之后,需要对功能做单元测试,需要项目有单元测试的功能,这个项目是一个新建的项目,所以需要自己弄,下面记载一下步骤。

首先,我们使用点击需要做单元测试的类名,右击使用idea自带生成单元测试文件的功能:
1.点击文件 -> GO TO -> Test
这里写图片描述
2.
这里写图片描述
3.
这里写图片描述
4.生成测试文件
这里写图片描述
5.加单元测试注解
这里写图片描述
6.在测试类中添加测试逻辑并运行
这里写图片描述

 

Spring Boot Junit 测试Controller

Controller:

 

[java] view plain copy print?

  1. package com.xiaolyuh.controller;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.data.domain.Page;  
  7. import org.springframework.data.domain.PageRequest;  
  8. import org.springframework.data.domain.Sort;  
  9. import org.springframework.data.domain.Sort.Direction;  
  10. import org.springframework.web.bind.annotation.RequestBody;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestParam;  
  13. import org.springframework.web.bind.annotation.RestController;  
  14.   
  15. import com.xiaolyuh.entity.Person;  
  16. import com.xiaolyuh.repository.PersonRepository;  
  17.   
  18. @RestController  
  19. public class DataController {  
  20.     // 1 Spring Data JPA已自动为你注册bean,所以可自动注入  
  21.     @Autowired  
  22.     PersonRepository personRepository;  
  23.   
  24.     /** 
  25.      * 保存 save支持批量保存:<S extends T> Iterable<S> save(Iterable<S> entities); 
  26.      *  
  27.      * 删除: 支持使用id删除对象、批量删除以及删除全部: void delete(ID id); void delete(T entity); 
  28.      * void delete(Iterable<? extends T> entities); void deleteAll(); 
  29.      *  
  30.      */  
  31.     @RequestMapping("/save")  
  32.     public Person save(@RequestBody Person person) {  
  33.   
  34.         Person p = personRepository.save(person);  
  35.   
  36.         return p;  
  37.   
  38.     }  
  39.   
  40.     /** 
  41.      * 测试findByAddress 
  42.      */  
  43.     @RequestMapping("/q1")  
  44.     public List<Person> q1(String address) {  
  45.   
  46.         List<Person> people = personRepository.findByAddress(address);  
  47.   
  48.         return people;  
  49.   
  50.     }  
  51.   
  52.     /** 
  53.      * 测试findByNameAndAddress 
  54.      */  
  55.     @RequestMapping("/q2")  
  56.     public Person q2(String name, String address) {  
  57.   
  58.         Person people = personRepository.findByNameAndAddress(name, address);  
  59.   
  60.         return people;  
  61.   
  62.     }  
  63.   
  64.     /** 
  65.      * 测试withNameAndAddressQuery 
  66.      */  
  67.     @RequestMapping("/q3")  
  68.     public Person q3(String name, String address) {  
  69.   
  70.         Person p = personRepository.withNameAndAddressQuery(name, address);  
  71.   
  72.         return p;  
  73.   
  74.     }  
  75.   
  76.     /** 
  77.      * 测试withNameAndAddressNamedQuery 
  78.      */  
  79.     @RequestMapping("/q4")  
  80.     public Person q4(String name, String address) {  
  81.   
  82.         Person p = personRepository.withNameAndAddressNamedQuery(name, address);  
  83.   
  84.         return p;  
  85.   
  86.     }  
  87.   
  88.     /** 
  89.      * 测试排序 
  90.      */  
  91.     @RequestMapping("/sort")  
  92.     public List<Person> sort() {  
  93.   
  94.         List<Person> people = personRepository.findAll(new Sort(Direction.ASC, "age"));  
  95.   
  96.         return people;  
  97.   
  98.     }  
  99.   
  100.     /** 
  101.      * 测试分页 
  102.      */  
  103.     @RequestMapping("/page")  
  104.     public Page<Person> page(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) {  
  105.   
  106.         Page<Person> pagePeople = personRepository.findAll(new PageRequest(pageNo, pageSize));  
  107.   
  108.         return pagePeople;  
  109.   
  110.     }  
  111.   
  112. }  
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?

  1. package com.xiaolyuh;  
  2.   
  3. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;  
  4. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;  
  5. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;  
  6.   
  7. import java.util.HashMap;  
  8. import java.util.Map;  
  9.   
  10. import org.junit.Before;  
  11. import org.junit.Test;  
  12. import org.junit.runner.RunWith;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.boot.test.context.SpringBootTest;  
  15. import org.springframework.http.MediaType;  
  16. import org.springframework.test.context.junit4.SpringRunner;  
  17. import org.springframework.test.web.servlet.MockMvc;  
  18. import org.springframework.test.web.servlet.MvcResult;  
  19. import org.springframework.test.web.servlet.setup.MockMvcBuilders;  
  20. import org.springframework.web.context.WebApplicationContext;  
  21.   
  22. import net.minidev.json.JSONObject;  
  23.   
  24. @RunWith(SpringRunner.class)  
  25. @SpringBootTest  
  26. public class SpringBootStudentDataJpaApplicationTests {  
  27.   
  28.     @Test  
  29.     public void contextLoads() {  
  30.     }  
  31.   
  32.     private MockMvc mockMvc; // 模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。    
  33.         
  34.     @Autowired    
  35.     private WebApplicationContext wac; // 注入WebApplicationContext    
  36.     
  37. //    @Autowired    
  38. //    private MockHttpSession session;// 注入模拟的http session    
  39. //        
  40. //    @Autowired    
  41. //    private MockHttpServletRequest request;// 注入模拟的http request\    
  42.     
  43.     @Before // 在测试开始前初始化工作    
  44.     public void setup() {    
  45.         this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();    
  46.     }    
  47.     
  48.     @Test    
  49.     public void testQ1() throws Exception {    
  50.         Map<String, Object> map = new HashMap<>();  
  51.         map.put("address", "合肥");  
  52.           
  53.         MvcResult result = mockMvc.perform(post("/q1?address=合肥").content(JSONObject.toJSONString(map)))  
  54.                 .andExpect(status().isOk())// 模拟向testRest发送get请求    
  55.                 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8    
  56.                 .andReturn();// 返回执行请求的结果    
  57.             
  58.         System.out.println(result.getResponse().getContentAsString());    
  59.     }    
  60.   
  61.     @Test    
  62.     public void testSave() throws Exception {    
  63.         Map<String, Object> map = new HashMap<>();  
  64.         map.put("address", "合肥");  
  65.         map.put("name", "测试");  
  66.         map.put("age", 50);  
  67.           
  68.         MvcResult result = mockMvc.perform(post("/save").contentType(MediaType.APPLICATION_JSON).content(JSONObject.toJSONString(map)))  
  69.                 .andExpect(status().isOk())// 模拟向testRest发送get请求    
  70.                 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8    
  71.                 .andReturn();// 返回执行请求的结果    
  72.           
  73.         System.out.println(result.getResponse().getContentAsString());    
  74.     }    
  75.   
  76.     @Test    
  77.     public void testPage() throws Exception {    
  78.         MvcResult result = mockMvc.perform(post("/page").param("pageNo", "1").param("pageSize", "2"))  
  79.                 .andExpect(status().isOk())// 模拟向testRest发送get请求    
  80.                 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8    
  81.                 .andReturn();// 返回执行请求的结果    
  82.           
  83.         System.out.println(result.getResponse().getContentAsString());    
  84.     }    
  85.   
  86. }  

 

转载:

https://blog.csdn.net/qq_33206732/article/details/79242107

https://blog.csdn.net/xiaolyuh123/article/details/73281522

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值