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分布式锁1
zookeeper集群的每个节点的数据都是一致的, 那么我们可以通过这些节点来作为锁的标志. 首先给锁设置一下API, 至少要包含, lock(锁住), unlock(解锁), isLocked(是否 ...
- String是基本的数据类型吗?
String不是基本的数据类型,是final修饰的java类,java中的基本类型一共有8个,它们分别为: 1 字符类型:byte,char 2 基本整型:short,int,long 3 浮点型:f ...
- SetConsoleCtrlHandler演示
#include "stdafx.h"#include <Windows.h> static BOOL WINAPI Handler(DWORD cntrlEvent) ...
- UML设计九种图例
一.作为一种建模语言,UML的定义包括UML语义和UML表示法两个部分. UML语义:描述基于UML的精确元模型定义. UML表示法:定义UML符号的表示法,为开发者或开发工具使用这些图形符号和文本语 ...
- maven中pom.xml元素含义
- android-auto-scroll-view-pager (无限广告轮播图)
github 地址: https://github.com/Trinea/android-auto-scroll-view-pager Gradle: compile ('cn.trinea.andr ...
- C#正则表达式匹配双引号
html: <img class="bubble large" src="/images/hero-logos/cog.svg" width=" ...
- while 用法 for 循环的总结
格式化输出.%s %d # name = input('请输入名字:') # age = input('请输入年龄:') # sex = input('请输入性别:') # # msg = '我的名字 ...
- Ros学习——roslaunch
roslaunch:启动定义在launch文件中的多个节点 1.launch文件解析 <launch> #以launch标签开头以表明这是一个launch文件 #两个节点分组并以'命名空间 ...
- c++的单例模式及c++11对单例模式的优化
单例模式 单例模式,可以说设计模式中最常应用的一种模式了,据说也是面试官最喜欢的题目.但是如果没有学过设计模式的人,可能不会想到要去应用单例模式,面对单例模式适用的情况,可能会优先考虑使用全局或者静态 ...