可以参考: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---表单验证

    重点: 1.表单的提交 2.触发blur事件 3.判断是否正确,提交与否 return False <!DOCTYPE html> <html lang="en" ...

  2. 【HAOI2013】花卉节

    HA果然是弱省中的弱省…… 原题: ZZ市准备在绿博园举办一次花卉节.Dr.Kong接受到一个任务,要买一批花卉进行布置园林.能投入买花卉的资金只有B元 (1 <= B <= 10^18) ...

  3. MySQL Transaction--RR事务隔离级别下加锁测试

    ============================================================================== 按照非索引列更新 在可重复读的事务隔离级别 ...

  4. 【Android界面实现】AppWidght全面学习之电量监控小部件的实现具体解释

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/bz419927089/article/details/35791047 前几天翻看之前下载的各种资料 ...

  5. nyoj 表达式求值

    35-表达式求值 内存限制:64MB 时间限制:3000ms Special Judge: Noaccepted:19 submit:26 题目描述: ACM队的mdd想做一个计算器,但是,他要做的不 ...

  6. SQL语言:DDL/DML/DQL/DCL

    SQL (Structure Query Language)语言是数据库的核心语言. SQL 的发展是从1974年开始的,其发展过程如下: 1974年-----由Boyce和Chamberlin提出, ...

  7. RK3288 wifi模块打开或关闭5G信号

    CPU:RK3288 系统:Android 5.1 如果硬件使用的wifi模块支持5G,则系统设置中打开wifi,除了会搜索到普通的2.4G信号,还会搜索到xxx_5G信号. 如果路由器开了5G信号, ...

  8. hello world之Makefile

    hello world之Makefile

  9. 关于Jquery 插件开发,写的很清楚了。。。

    转自:http://blog.jobbole.com/30550/ 本文由 伯乐在线 - 戴嘉华 翻译.未经许可,禁止转载!英文出处:Extraordinarythoughts.欢迎加入翻译小组. 如 ...

  10. 从云端到边缘 AI推动FPGA应用拓展

    近日,全球最大的FPGA厂商赛灵思宣布收购深鉴科技的消息,引发人工智能芯片行业热议,这也是首起中国AI芯片公司被收购的案例.值得注意的是,收购深鉴科技的赛灵思在2018年下半年重点发展方面是汽车自动驾 ...