原文链接: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. Spring之3:BeanFactory、ApplicationContext、ApplicationContextAware区别

    在Spring中系统已经为用户提供了许多已经定义好的容器实现,而不需要开发人员事必躬亲.相比那些简单拓展BeanFactory的基本IoC容器,开发人员常用的ApplicationContext除了能 ...

  2. 开发环境无错,部署至测试环境报错“NoSuchMethodError”OR"NoSuchClassError"

    背景: 实现一个简单的功能,需要用到jedis的jar包连接Redis.在之前便已经有使用jedis,它的版本比较旧,是2.1的.而新实现的功能,在编码的时候使用的是2.8的.在开发环境完成单元测试后 ...

  3. Weblogic wls RCE 漏洞验证POC

    #!/usr/bin/env python # coding:utf-8 # @Date : 2017/12/22 17:11 # @File : weblogic_poc.py # @Author ...

  4. python中的 ' ' 和 " "

    #!/usr/bin/python import MySQLdb try: conn = MySQLdb.connect(host = 'localhost', user = 'root', pass ...

  5. Socket编程, 在server端read()函数调用后显示错误:Transport endpoint is not connected (犯了低级错误)

    for(;;){ socklen_t len = sizeof(client_address); connfd = accept(listenfd, (struct sockaddr *)&c ...

  6. 注解:@interface 自定义注解的语法

      自定义注解: 使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节.在定义注解时,不能继承其他的注解或接口 ...

  7. Centos 7.2 编译安装 git

    一. 下载最新版GIT安装包: https://www.kernel.org/pub/software/scm/git/ 选择想要安装的版本,下载,解压 命令: .tar.gz $ cd git- 二 ...

  8. 生产环境该如何选择lvs的工作模式,和哪一种算法

    lvs的工作模式有这几种: 1.RR : 轮叫算法,平均分配,你一个,我一个: 2.WRR :加权轮叫算法,谁的处理能力强,谁的权重就高: 3.LC :最少链接算法,谁的连接数最少,谁就处理更多的链接 ...

  9. 类型:.net;问题:asp.net window验证;结果:细说ASP.NET Windows身份认证

    细说ASP.NET Windows身份认证 阅读目录 开始 认识ASP.NET Windows身份认证 访问 Active Directory 在ASP.NET中访问Active Directory ...

  10. 用UltraISO把硬盘文件制作成ISO格式

    转自:https://wenku.baidu.com/view/0052c88dcc22bcd126ff0cbf.html 用UltraISO把硬盘文件制作成ISO格式方法: 制作硬盘ISO文件步骤一 ...