原文链接: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. Canvas 与 SVG 的比较

    Canvas:<canvas> 标签定义图形(只是图形容器),比如图表和其他图像,您必须使用脚本 (通常是JavaScript)来绘制图形.默认情况下 <canvas> 元素没 ...

  2. Weblogic wls RCE 漏洞验证POC

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

  3. vuex的实用知识点

    本文系统介绍vuex的全部内容 为什么用vuex 组件通信知道吧,相信很多同学,刚学的时候很难懂,实时上在实际应用中,大型项目如果使用最原始的组件通信会非常的麻烦,主要体现在多层嵌套的组件之间的通信, ...

  4. 如何使32位Linux支持4G以上内存

    问题 Linux无法支持超过4G的内存,笔者使用的Linux是CentOS 5,机器是DELL PE1950服务器.    原因: X86系统默认寻址能力的限制    解决办法: 安装具有PAE(物理 ...

  5. Json-lib 进行java与json字符串转换之二

    二.list和json字符串的互转 list-->>json字符串 public static void listToJSON(){ Student stu=new Student(); ...

  6. Javascript ——Navigator对象

    见 <Javascript 高级程序设计 第二版> P172 一.检测插件: 1.获取所有插件名称: 非IE浏览器:根据plugins数组, function getplugins() { ...

  7. SQLServer SDK

    https://www.cnblogs.com/Leo_wl/p/3451865.html 回到目录 SQLSERVER一些公用DLL的作用解释 如果你的SQLSERVER安装在C盘的话,下面的路径就 ...

  8. 用JS,打印正立三角形

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  9. 第二天:tomcat体系结构和第一个Servlet

    1.  打war包 2.  Tomcat体系再说明:   问题:如何去配置默认主机???    3.tomcat和servlet在网络中的位置 4.    servlet快速入门案例   1).开发s ...

  10. MySql 5.7中添加用户,新建数据库,用户授权,删除用户,修改密码

    转自http://blog.csdn.net/w690333243/article/details/76576952 1.新建用户 创建test用户,密码是1234. MySQL -u root -p ...