SpringBoot Junit测试Controller
原文链接:https://blog.csdn.net/xiaolyuh123/article/details/73281522
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; } }
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());
} }
SpringBoot Junit测试Controller的更多相关文章
- spring boot(三)Junit 测试controller
Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法 一.单元测试的目的 简单来说就是在我们增加或者改动一些代码以后对所有逻辑的一个检测,尤其是在我们后期 ...
- springboot+junit测试
文章目录 一.junit断言 二.测试模块 三.使用Mockito作为桩模块 四.使用mockMvc测试web层 五.批量测试和测试覆盖率 参考视频:用Spring Boot编写RESTful API ...
- Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法
一.单元测试的目的 简单来说就是在我们增加或者改动一些代码以后对所有逻辑的一个检测,尤其是在我们后期修改后(不论是增加新功能,修改bug),都可以做到重新测试的工作.以减少我们在发布的时候出现更过甚至 ...
- mybatis-generator没有自动生成代码和Junit测试controller
本来mybatis的generator想要自动生成增删改的,但是到后来语句就两个select,原因是数据中没有给字段加primary,就不会有删改增. 以及Controller的Junit测试 先导入 ...
- Junit测试Controller(MockMVC使用),以及传输@RequestBody数据解决办法
转自:http://www.importnew.com/21153.html 一.单元测试的目的 简单来说就是在我们增加或者改动一些代码以后对所有逻辑的一个检测,尤其是在我们后期修改后(不论是增加新功 ...
- springmvc controller junit 测试
第一次搭建SSM框架,整合SpringMVC完成后进行Controller测试,找资料并解决问题. 下图是我的完整目录: 1 建立UserController类 代码清单 1-1:UserContro ...
- springBoot中使用使用junit测试文件上传,以及文件下载接口编写
本篇文章将介绍如何使junit在springBoot中测试文件的上传,首先先阅读如何在springBoot中进行接口测试. 文件上传操作测试代码 import org.junit.Before; im ...
- Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用
==============Springboot的日志管理============= springboot无需引入日志的包,springboot默认已经依赖了slf4j.logback.log4j等日 ...
- ssm框架中Controller层的junit测试_我改
Controller测试和一般其他层的junit测试可以共用一个BaseTest 一.BaseTest如下: @RunWith(SpringJUnit4ClassRunner.class) @WebA ...
随机推荐
- Zookeeper学习(八):Zookeeper的数据发布与订阅模式
http://blog.csdn.net/ZuoAnYinXiang/article/category/6104448 1.发布订阅的基本概念 1.发布订阅模式可以看成一对多的关系:多 ...
- 从CoreAnimation到Pop
pop是Facebook在开源的一款动画引擎,看下其官方的介绍: Pop是一款在iOS.tvOS和OS X平台通用的可扩展动画引擎.它在基本静态动画的基础上,增加了弹性以及衰减动画,这在创建真实有物里 ...
- 超详细的Maven使用教程
原文: http://blog.csdn.net/u010425776/article/details/52027706 主题 Maven 什么是Maven? 如今我们构建一个项目需要用到很多第三方 ...
- pthon爬虫(9)--Selenium的用法
简介 Selenium 是什么?一句话,自动化测试工具.它支持各种浏览器,包括 Chrome,Safari,Firefox 等主流界面式浏览器,如果你在这些浏览器里面安装一个 Selenium 的插件 ...
- eclipse 中使用 GreenUML 和 AmasterasUML 自动生成类图
Green UML和AmaterasUML 两种 一.安装方法: 1.都是先安装GEF 通过eclipse-> install new software安装GEF的网址: http://down ...
- Webview离线功能(优先cache缓存+cache缓存管理)
在做Webview显示服务器的html功能时 需要加入离线功能. 开始思路很狭隘,以为一定应该是从服务器得到的html文件,下载到本地后加载~ 但是这样不能离线查看图片,因为图片数据并不再html中, ...
- PHP的count(数组)和strlen(字符串)的内部实现
PHP的count(数组)和strlen(字符串)的内部实现上是直接显示一个长度变量,还是重头依次数一遍有多少个元素?关乎我理解这2个函数的效率..希望高人能从php的c源码上讲一讲.没有源码看过源码 ...
- array_unique() 函数移除数组中的重复的值
array_unique() 函数移除数组中的重复的值,并返回结果数组. 当几个数组元素的值相等时,只保留第一个元素,其他的元素被删除. 返回的数组中键名不变.
- 一个典型的PHP分页实例代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- SQL语句兼容性规范
一.DDL兼容性规范(防止表结构变更后,原有的SQL执行报错)只能增加字段或修改字段长度(字段长度改大),不能修改字段名字和类型,不能删除字段不能删除表或者修改表名称 二.DML兼容性规范insert ...