mock——test 基本所有使用
可以参考: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 基本所有使用的更多相关文章
- 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 ...
- Google C++单元测试框架GoogleTest---Google Mock简介--概念及基础语法
就在昨天终于做了gtest的分享,我的预研工作终于结束了,感觉离我辞职的日子不远了,毕竟是专注java二百年啊,要告别实习啦.. 这篇是GoogleMock的简介文档,会在后边附带一个自己的例子. 一 ...
- Pramp - mock interview experience
Pramp - mock interview experience February 23, 2016 Read the article today from hackerRank blog on ...
- Spring Mock
今天看别人的测试代码,发现有 MockMvc.MockHttpServletRequest.MockHttpServletResponse ,不知道是干啥的,百度下下才知道 Mock这个东东. 下 ...
- Python mock
在测试过程中,为了更好地展开单元测试,mock一些数据跟对象在所难免,下面讲一下python的mock的简单用法. 关于python mock,网上有很多资料,这里不会讲的特别深,但一定会是实用为主, ...
- ABP中单元测试的技巧:Mock和数据驱动
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:虽然ABP为大家提供了测试的脚手架了,不过有些小技巧还是需要自己探索的. ASP.NE ...
- [转] 前后端分离开发模式的 mock 平台预研
引入 mock(模拟): 是在项目测试中,对项目外部或不容易获取的对象/接口,用一个虚拟的对象/接口来模拟,以便测试. 背景 前后端分离 前后端仅仅通过异步接口(AJAX/JSONP)来编程 前后端都 ...
- 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 ...
- Nova PhoneGap框架 第六章 使用Mock
在我们的框架中引入了一个很重要的设计,那就是使用Mock. 这里的mock是指cordova.mock.js文件,它模拟了PhoneGap(Cordova)的API,从而可以在浏览器中运行测试我们的程 ...
- mock.js
mock.js http://mockjs.com/ https://github.com/nuysoft/Mock/wiki 为了完成angularjs的karma测试,看到这个好东东,这货能拦截a ...
随机推荐
- CH4302 Interval GCD
题意 4302 Interval GCD 0x40「数据结构进阶」例题 描述 给定一个长度为N的数列A,以及M条指令 (N≤5*10^5, M<=10^5),每条指令可能是以下两种之一: &qu ...
- C条件编译
#include <stdio.h> void main() { #ifdef AAA printf("find AAA defined\n"); #else prin ...
- 单变量微积分笔记20——三角替换1(sin和cos)
sin和cos的常用公式 基本公式: 半角公式: 微分公式: 积分公式: 三角替换 示例1 根据微分公式,cosxdx = dsinx 示例2 示例3 半角公式 示例1 示例2 解法1: 解法2: 综 ...
- 【转】每天一个linux命令(34):du 命令
原文网址:http://www.cnblogs.com/peida/archive/2012/12/10/2810755.html Linux du命令也是查看使用空间的,但是与df命令不同的是Lin ...
- oracle单表选择率(selectivity)——计算执行计划的基数
CBO优化器是基于对当前经过特定测试的数据集中预期的行比率估计来计算基数的.此处的行数之比是一个数值,称为选择率(selectivity).得到选择率之后,将其与输入行数进行简单相乘既可得到基数. 在 ...
- hosts,No web site is configured at this address.
解决办法: IIS管理器->右击网站->属性->网站——>IP地址一项->选择全部未分配-> 确定关闭 问题解决.
- java.net.SocketTimeoutException: Read timed out 错误解决
这两天项目在测试环境下通过URLConnection 做数据传递时,出现了如下错误 java.net.SocketTimeoutException: Read timed out 经过查找研究,原因是 ...
- gcc gdb调试 (三)
编写代码过程中少不了调试.在windows下面,我们有visual studio工具.在linux下面呢,实际上除了gdb工具之外,你没有别的选择.那么,怎么用gdb进行调试呢?我们可以一步一步来试试 ...
- Android 自定义 spinner (背景、字体颜色)
转自:http://blog.sina.com.cn/s/blog_3e333c4a010151cj.html 1.准备两张图片,并做好9.png 2.在drawable中定义spinner_se ...
- signal简述
一个几乎是最简单的应用如下: #include <unistd.h> // for alarm() #include <signal.h> // for signal() #i ...