可以参考: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. 前端jquery学习--03

    1.tab切换 <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  2. CTF-练习平台-Misc之 听首音乐

    十九.听首音乐 用软件audacity打开后发现如下 上面那一行是可以看做摩斯电码,翻译过来是: ..... -... -.-. ----. ..--- ..... -.... ....- ----. ...

  3. $.grep()的用法

    grep()方法用于数组元素过滤筛选 grep(array,callback,invert) array:待过滤数组; callback:处理数组中的每个元素,并过滤元素,该函数中包含两个参数,第一个 ...

  4. (领悟)第一个servlet

    //这个代码不可以写在javase的project文件里面//要写在动态web工程里面,不需要配置文件,不需要jsp,只需jar包的帮助(url跳转的必须是java-web文件) import jav ...

  5. 【转】【iOS】动态更换App图标

    原文网址:http://www.cocoachina.com/ios/20170619/19557.html 前言 动态更换App图标这件事,在用户里总是存在需求的:有些用户喜欢“美化”自己的手机.至 ...

  6. post请求(headers里有属性)报错:Request header field xxx is not allowed by Access-Control-Allow-Headers in preflight response

    post 请求,headers里有属性(xxx).请求时报错: XMLHttpRequest cannot load <url>. Request header field xxx is ...

  7. 关于 Cookie-free Domains (为什么将静态图片,js,css存放到单独的域名?)

    这篇文章对高性能web开发具有参考性:http://developer.yahoo.com/performance/rules.html 本文主要描述使用裸域名做网站主域名时,如何用子域名做 cook ...

  8. MySQL中drop,truncate 和delete的区别

    注意:这里说的delete是指不带where子句的delete语句 相同点: truncate和不带where子句的delete, 以及drop都会删除表内的数据 不同点: truncate和 del ...

  9. POJ2392 Space Elevator

    题目:http://poj.org/problem?id=2392 一定要先按高度限制由小到大排序! 不然就相当于指定了一个累加的顺序,在顺序中是不能做到“只放后面的不放前面的”这一点的! 数组是四十 ...

  10. Spring Cloud 入门 之 Config 篇(六)

    原文地址:Spring Cloud 入门 之 Config 篇(六) 博客地址:http://www.extlight.com 一.前言 随着业务的扩展,为了方便开发和维护项目,我们通常会将大项目拆分 ...