可以参考:http://www.cnblogs.com/lyy-2016/p/6122144.html

test

/**
*
*/
package com.imooc.web.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date; 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.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; /**
* @author zhailiang
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest { @Autowired
private WebApplicationContext wac; private MockMvc mockMvc; @Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void whenUploadSuccess() throws Exception {
String result = mockMvc.perform(fileUpload("/file")
.file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello upload".getBytes("UTF-8"))))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
} @Test
public void whenQuerySuccess() throws Exception {
String result = mockMvc.perform(
get("/user").param("username", "jojo").param("age", "18").param("ageTo", "60").param("xxx", "yyy")
// .param("size", "15")
// .param("page", "3")
// .param("sort", "age,desc")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk()).andExpect(jsonPath("$.length()").value(3))
.andReturn().getResponse().getContentAsString(); System.out.println(result);
} @Test
public void whenGetInfoSuccess() throws Exception {
String result = mockMvc.perform(get("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("tom"))
.andReturn().getResponse().getContentAsString(); System.out.println(result);
} @Test
public void whenGetInfoFail() throws Exception {
mockMvc.perform(get("/user/a")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().is4xxClientError());
} @Test
public void whenCreateSuccess() throws Exception { Date date = new Date();
System.out.println(date.getTime());
String content = "{\"username\":\"tom\",\"password\":null,\"birthday\":"+date.getTime()+"}";
String reuslt = mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("1"))
.andReturn().getResponse().getContentAsString(); System.out.println(reuslt);
} @Test
public void whenCreateFail() throws Exception { Date date = new Date();
System.out.println(date.getTime());
String content = "{\"username\":\"tom\",\"password\":null,\"birthday\":"+date.getTime()+"}";
String reuslt = mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
// .andExpect(status().isOk())
// .andExpect(jsonPath("$.id").value("1"))
.andReturn().getResponse().getContentAsString(); System.out.println(reuslt);
} @Test
public void whenUpdateSuccess() throws Exception { Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println(date.getTime());
String content = "{\"id\":\"1\", \"username\":\"tom\",\"password\":null,\"birthday\":"+date.getTime()+"}";
String reuslt = mockMvc.perform(put("/user/1").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("1"))
.andReturn().getResponse().getContentAsString(); System.out.println(reuslt);
} @Test
public void whenDeleteSuccess() throws Exception {
mockMvc.perform(delete("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
} }

controller代码

/**
*
*/
package com.imooc.web.controller; import java.util.ArrayList;
import java.util.List; import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid; import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest; import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.dto.User;
import com.imooc.dto.UserQueryCondition; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; /**
* @author zhailiang
*
*/
@RestController
@RequestMapping("/user")
public class UserController { @Autowired
private ProviderSignInUtils providerSignInUtils; @PostMapping("/regist")
public void regist(User user, HttpServletRequest request) { //不管是注册用户还是绑定用户,都会拿到一个用户唯一标识。
String userId = user.getUsername();
providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
} @GetMapping("/me")
public Object getCurrentUser(@AuthenticationPrincipal UserDetails user) {
return user;
} @PostMapping
@ApiOperation(value = "创建用户")
public User create(@Valid @RequestBody User user) { System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday()); user.setId("1");
return user;
} @PutMapping("/{id:\\d+}")
public User update(@Valid @RequestBody User user, BindingResult errors) { System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday()); user.setId("1");
return user;
} @DeleteMapping("/{id:\\d+}")
public void delete(@PathVariable String id) {
System.out.println(id);
} @GetMapping
@JsonView(User.UserSimpleView.class)
@ApiOperation(value = "用户查询服务")
public List<User> query(UserQueryCondition condition,
@PageableDefault(page = 2, size = 17, sort = "username,asc") Pageable pageable) { System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE)); System.out.println(pageable.getPageSize());
System.out.println(pageable.getPageNumber());
System.out.println(pageable.getSort()); List<User> users = new ArrayList<>();
users.add(new User());
users.add(new User());
users.add(new User());
return users;
} @GetMapping("/{id:\\d+}")
@JsonView(User.UserDetailView.class)
public User getInfo(@ApiParam("用户id") @PathVariable String id) {
// throw new RuntimeException("user not exist");
System.out.println("进入getInfo服务");
User user = new User();
user.setUsername("tom");
return user;
} }

参考1:https://www.cnblogs.com/lyy-2016/p/6122144.html

参考2:https://www.cnblogs.com/xiaohunshi/p/5706943.html

参考3:https://blog.csdn.net/zhang289202241/article/details/62042842?locationNum=9&fps=1

mock——test 基本所有使用的更多相关文章

  1. Pramp mock interview (4th practice): Matrix Spiral Print

    March 16, 2016 Problem statement:Given a 2D array (matrix) named M, print all items of M in a spiral ...

  2. Google C++单元测试框架GoogleTest---Google Mock简介--概念及基础语法

    就在昨天终于做了gtest的分享,我的预研工作终于结束了,感觉离我辞职的日子不远了,毕竟是专注java二百年啊,要告别实习啦.. 这篇是GoogleMock的简介文档,会在后边附带一个自己的例子. 一 ...

  3. Pramp - mock interview experience

    Pramp - mock interview experience   February 23, 2016 Read the article today from hackerRank blog on ...

  4. Spring Mock

    今天看别人的测试代码,发现有  MockMvc.MockHttpServletRequest.MockHttpServletResponse ,不知道是干啥的,百度下下才知道  Mock这个东东. 下 ...

  5. Python mock

    在测试过程中,为了更好地展开单元测试,mock一些数据跟对象在所难免,下面讲一下python的mock的简单用法. 关于python mock,网上有很多资料,这里不会讲的特别深,但一定会是实用为主, ...

  6. ABP中单元测试的技巧:Mock和数据驱动

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:虽然ABP为大家提供了测试的脚手架了,不过有些小技巧还是需要自己探索的. ASP.NE ...

  7. [转] 前后端分离开发模式的 mock 平台预研

    引入 mock(模拟): 是在项目测试中,对项目外部或不容易获取的对象/接口,用一个虚拟的对象/接口来模拟,以便测试. 背景 前后端分离 前后端仅仅通过异步接口(AJAX/JSONP)来编程 前后端都 ...

  8. What's the difference between a stub and mock?

    I believe the biggest distinction is that a stub you have already written with predetermined behavio ...

  9. Nova PhoneGap框架 第六章 使用Mock

    在我们的框架中引入了一个很重要的设计,那就是使用Mock. 这里的mock是指cordova.mock.js文件,它模拟了PhoneGap(Cordova)的API,从而可以在浏览器中运行测试我们的程 ...

  10. mock.js

    mock.js http://mockjs.com/ https://github.com/nuysoft/Mock/wiki 为了完成angularjs的karma测试,看到这个好东东,这货能拦截a ...

随机推荐

  1. 《DSP using MATLAB》Problem 3.6

    逆DTFT定义如下: 需要求积分,

  2. hdu 1203 dp(关于概率的```背包?)

    题意:一个人手里有一笔钱 n ,有 m 所大学,分别知道这些大学的投简历花费和被录取概率,因为钱数有限,只能投一部分学校,问被录取的概率最大有多大. 这题除去计算概率以外就是一个 0 1 背包问题,所 ...

  3. 部署tomcat到Linux

    1. alt+p   放文件 2.解压到自定义 apps文件夹中 tar -zxvf apache-tomcat-7.0.68.tar.gz -C apps 3.进入文件启动tomcat/bin ./ ...

  4. socat 广播以及多播

    官方文档有一个关于组播,多播的例子挺不错,记录下 多播客户端以及服务器 注意地址修改为自己的网络 server socat UDP4-RECVFROM:6666,ip-add-membership=2 ...

  5. binlog cache size设置是否合理判断

    二进制日志是写操作是,首先写入二进制日志缓冲(binlog_cache)然后commit,再从binlog_cache写入到binlog文件,默认大小为32K,而binlog_cache是sessio ...

  6. Sql Server Report Service 的部署问题

    近期在研究SSRS部署问题,因为以前也用到过SSRS报表,但当时开发的报表是有专门的集成系统的,不需要我自己去部署,所以对这一块的部署也不熟悉,我记得当时我是直接开发出一个SSRS 报表,然后会通过自 ...

  7. VS起始页不显示最近使用的项目解决方案

    前段时间换了一家公司,做ASP.NET开发,让我郁闷的是VS的起始页总是不显示最近使用项目,起先没在意,后来觉得越来越不方便了,然后本着内事不决问百度,外事不决问谷歌的态度,我就百了下~,结果还真遇到 ...

  8. TFS错误-TF249053

    前几天规划了下代码结构,改了很多东西后,台式机依然正常访问,但是笔记本一连接或者更改TFS相关资源就报错TF249053.报错点击后不影响正常使用,但是很郁闷.于是查了下资料如下. 错误原因: htt ...

  9. VS2010安装选项中有个“图标库”

    位置 :\Program Files\Microsoft Visual Studio 10.0\Common7\VS2010ImageLibrary\2052\VS2010ImageLibrary.z ...

  10. Java技术专题之JVM逻辑内存回收机制研究图解版

    一.引言 JVM虚拟机内存回收机曾迷惑了不少人,文本从JVM实现机制的角度揭示JVM内存回收的原理和机制. 一.Java平台逻辑架构 二.JVM物理结构 通过从JVM物理结构图我们可以看到: 1.JV ...