原文链接: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的更多相关文章

  1. spring boot(三)Junit 测试controller

    Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法 一.单元测试的目的 简单来说就是在我们增加或者改动一些代码以后对所有逻辑的一个检测,尤其是在我们后期 ...

  2. springboot+junit测试

    文章目录 一.junit断言 二.测试模块 三.使用Mockito作为桩模块 四.使用mockMvc测试web层 五.批量测试和测试覆盖率 参考视频:用Spring Boot编写RESTful API ...

  3. Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法

    一.单元测试的目的 简单来说就是在我们增加或者改动一些代码以后对所有逻辑的一个检测,尤其是在我们后期修改后(不论是增加新功能,修改bug),都可以做到重新测试的工作.以减少我们在发布的时候出现更过甚至 ...

  4. mybatis-generator没有自动生成代码和Junit测试controller

    本来mybatis的generator想要自动生成增删改的,但是到后来语句就两个select,原因是数据中没有给字段加primary,就不会有删改增. 以及Controller的Junit测试 先导入 ...

  5. Junit测试Controller(MockMVC使用),以及传输@RequestBody数据解决办法

    转自:http://www.importnew.com/21153.html 一.单元测试的目的 简单来说就是在我们增加或者改动一些代码以后对所有逻辑的一个检测,尤其是在我们后期修改后(不论是增加新功 ...

  6. springmvc controller junit 测试

    第一次搭建SSM框架,整合SpringMVC完成后进行Controller测试,找资料并解决问题. 下图是我的完整目录: 1 建立UserController类 代码清单 1-1:UserContro ...

  7. springBoot中使用使用junit测试文件上传,以及文件下载接口编写

    本篇文章将介绍如何使junit在springBoot中测试文件的上传,首先先阅读如何在springBoot中进行接口测试. 文件上传操作测试代码 import org.junit.Before; im ...

  8. Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用

    ==============Springboot的日志管理============= springboot无需引入日志的包,springboot默认已经依赖了slf4j.logback.log4j等日 ...

  9. ssm框架中Controller层的junit测试_我改

    Controller测试和一般其他层的junit测试可以共用一个BaseTest 一.BaseTest如下: @RunWith(SpringJUnit4ClassRunner.class) @WebA ...

随机推荐

  1. 删除pool error的解决方法

    标签(空格分隔): ceph,ceph运维,pool 问题描述: 删除pool的时候提示下面的错误: [root@node3 ~]# ceph osd pool delete ecpool ecpoo ...

  2. 查看osdmap命令

    标签(空格分隔): ceph,ceph运维,osdmap 方法一: 最直接,简单的命令: [root@node3 ~]# ceph osd tree ID CLASS WEIGHT TYPE NAME ...

  3. List<T> JIT 分配策略

    参考 http://www.cnblogs.com/brookshi/p/5353021.html defaultCapacity意思是new List<T>时默认大小是4. _items ...

  4. 【转】js获取对象的所有属性和方法

    //有时候需要知道一个js对像的所有属性和方法来帮助调试,下面是再网上找到的一个比较给力的方法 function displayProp(obj){ var names=""; f ...

  5. md5加密(1)

    package com.js.ai.modules.pointwall.util; import java.security.MessageDigest; import java.security.N ...

  6. 2016.5.30让窗口处于最顶层的方法,比TopMost灵活

    最简单的方法Form. Activate() 稍复杂的方法用API,目前没有看出比第一种方法有什么好处(可操作其它窗口,这就是好处2016.7.31) [System.Runtime.InteropS ...

  7. VotingClassifier

    scores : array of float, shape=(len(list(cv)),) Array of scores of the estimator for each run of the ...

  8. vue开发后台管理系统小结

    最近工作需要用vue开发了后台管理系统,由于是第一次开发后台管理系统,中间也遇到了一些坑,想在这里做个总结,也算是对于自己工作的一个肯定.我们金融性质的网站所以就不将代码贴出来哈 一.项目概述 首先工 ...

  9. DAY14-前端之Bootstrap框架

    Bootstrap介绍 Bootstrap是Twitter开源的基于HTML.CSS.JavaScript的前端框架. 它是为实现快速开发Web应用程序而设计的一套前端工具包. 它支持响应式布局,并且 ...

  10. DAY12-前端之HTML

    一.html初识 web服务本质 import socket def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...