整个项目结构:

定义user实体类

package com.mlxs.springboot.dto;

import java.util.HashMap;
import java.util.Map; /**
* User类描述:
*
* @author yangzhenlong
* @since 2017/2/13
*/
public class User { private int id;
private String name; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public static Map<Integer, User> buildUserList(){
Map<Integer, User> userMap = new HashMap<>(); for(int i=1; i<=5; i++){
User user = new User();
user.setId(i);
user.setName("测试" + i);
userMap.put(i, user);
} return userMap;
}
}

MainApp启动类:

package com.mlxs.springboot.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext; /**
* MainApp类描述:
*
* @author yangzhenlong
* @since 2017/2/13
*/
@SpringBootApplication
public class MainApp { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(MainApp.class, args);
/*String[] beanDefinitionNames = context.getBeanDefinitionNames();
System.out.println("-------- bean名称打印 --------");
for (String name : beanDefinitionNames) {
System.out.println(name);
}*/
}
}

UserService接口类:

public interface UserService {

    /**
* 查询所有用户
* @return
*/
Map<Integer, User> getAllUsers(); /**
* 根据Id查询
* @param id
* @return
*/
User getUserById(Integer id); /**
* 更新
* @param user
* @return
*/
User updateUserById(User user); /**
* 添加
* @param user
* @return
*/
User addUser(User user); /**
* 删除
* @param id
* @return
*/
boolean deleteUser(Integer id);
}

Service实现类:

@Service
public class UserServiceImpl implements UserService{ private static Map<Integer, User> userMap = User.buildUserList(); /**
* 查询所有用户
* @return
*/
public Map<Integer, User> getAllUsers(){
return userMap;
} /**
* 根据Id查询
* @param id
* @return
*/
public User getUserById(Integer id){
return userMap.get(id);
} /**
* 更新
* @param user
* @return
*/
public User updateUserById(User user){
if(null == userMap.get(user.getId())){
throw new RuntimeException("用户不存在");
}
userMap.put(user.getId(), user);
return user;
} /**
* 添加
* @param user
* @return
*/
public User addUser(User user){
if(null != userMap.get(user.getId())){
throw new RuntimeException("用户已存在");
}
userMap.put(user.getId(), user);
return user;
} /**
* 删除
* @param id
* @return
*/
public boolean deleteUser(Integer id){
if(null == userMap.get(id)){
throw new RuntimeException("用户不存在");
}
userMap.remove(id);
return true;
}
}

rest接口类UserController:

@RestController()
@RequestMapping("/")
public class UserController { private static Map<Integer, User> userMap = User.buildUserList(); /**
* 查询所有用户
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.GET)
public Map<Integer, User> getAllUsers(){
return userMap;
} /**
* 根据Id查询
* @param id
* @return
*/
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public User getUserById(Integer id){
return userMap.get(id);
} /**
* 更新
* @param user
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.PUT)
public User updateUserById(User user){
if(null == userMap.get(user.getId())){
throw new RuntimeException("用户不存在");
}
userMap.put(user.getId(), user);
return user;
} /**
* 添加
* @param user
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.POST)
public User addUser(User user){
if(null != userMap.get(user.getId())){
throw new RuntimeException("用户已存在");
}
userMap.put(user.getId(), user);
return user;
} /**
* 删除
* @param id
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.DELETE)
public String deleteUser(Integer id){
if(null == userMap.get(id)){
throw new RuntimeException("用户不存在");
}
userMap.remove(id);
return "delete success";
}
}

1.mockmvc针对service的单元测试:

UserServiceTest
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mlxs.springboot.dto.User;
import com.mlxs.springboot.web.MainApp;
import com.mlxs.springboot.web.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /**
* UserWebTest类描述:
*
* @author yangzhenlong
* @since 2017/2/13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MainApp.class)
public class UserServiceTest { @Autowired
private UserService userService;
@Autowired
private ObjectMapper om; @Test
public void testAll() throws JsonProcessingException {
this.list();
this.add();
this.update();
this.delete();
} @Test
public void list() throws JsonProcessingException {
System.out.println("\n----------查询----------");
this.print(userService.getAllUsers());
} @Test
public void add(){
System.out.println("\n----------添加----------");
User add = new User();
add.setId(10);
add.setName("这是新添加");
userService.addUser(add);
this.print(userService.getAllUsers());
} @Test
public void update(){
System.out.println("\n----------更新----------");
User user = userService.getUserById(2);
user.setName("测试222");
userService.updateUserById(user);
this.print(userService.getAllUsers());
} @Test
public void delete(){
System.out.println("\n----------删除----------");
userService.deleteUser(3);
this.print(userService.getAllUsers());
} private void print(Object obj){
try {
System.out.println(om.writeValueAsString(obj));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}

执行testAll()方法结果:

2.mockmvc针对rest接口类的测试:

UserWebTest:
import com.mlxs.springboot.web.UserController;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; /**
* UserWebTest类描述:
*
* @author yangzhenlong
* @since 2017/2/13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MockServletContext.class)
@WebAppConfiguration //启动一个真实web服务,然后调用Controller的Rest API,待单元测试完成之后再将web服务停掉
public class UserWebTest { private MockMvc mockMvc; @Before
public void setMockMvc(){
mockMvc = MockMvcBuilders.standaloneSetup(new UserController()).build();//设置要mock的Controller类,可以是多个
} @Test
public void testAll() throws Exception {
//1.查询
String queryResult = mockMvc.perform(MockMvcRequestBuilders.get("/user"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("id")))
.andReturn().getResponse().getContentAsString();
System.out.println("----------查询----------\n" + queryResult);
//2.添加
String addResult = mockMvc.perform(MockMvcRequestBuilders.post("/user").param("id", "10").param("name", "新添加"))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("----------添加----------\n" + addResult);
//3.更新
String updateResult = mockMvc.perform(MockMvcRequestBuilders.put("/user").param("id", "3").param("name", "更新333"))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("----------更新----------\n" + updateResult);
//4.删除
String deleteResult = mockMvc.perform(MockMvcRequestBuilders.delete("/user").param("id", "1"))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("----------删除----------\n" + deleteResult);
}
}

执行testAll()方法后结果:

springboot03-unittest mockmvc单元测试的更多相关文章

  1. Python+selenium+unittest+HTMLTestReportCN单元测试框架分享

    分享一个比较基础的,系统性的知识点.Python+selenium+unittest+HTMLTestReportCN单元测试框架分享 Unittest简介 unittest是Python语言的单元测 ...

  2. Python Unittest 自动化单元测试框架Demo

    python 测试框架(本文只涉及 PyUnit) https://wiki.python.org/moin/PythonTestingToolsTaxonomy 环境准备 首先确定已经安装有Pyth ...

  3. python 使用unittest进行单元测试

    import unittest import HTMLTestRunner """ Python中有一个自带的单元测试框架是unittest模块,用它来做单元测试,它里面 ...

  4. SpringBoot基础之MockMvc单元测试

    SpringBoot创建的Maven项目中,会默认添加spring-boot-starter-test依赖.在<5分钟快速上手SpringBoot>中编写的单元测试使用了MockMvc.本 ...

  5. python模块详解 | unittest(单元测试框架)(持续更新中)

    目录: why unittest? unittest的四个重要概念 加载测试用例的三个方法 自动加载测试用例 忽略测试和预期失败 生成html测试报告 why unittest? 简介: Unitte ...

  6. SpringMvc框架MockMvc单元测试注解及其原理分析

    来源:https://www.yoodb.com/ 首先简单介绍一下Spring,它是一个轻量级开源框架,简单的来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开 ...

  7. 使用Unittest做单元测试,addTest()单个case的时候却执行全部的case

    参考: http://tieba.baidu.com/p/6008699660 首先造成这个结果的原因是pycharm配置问题 问题验证: 测试代码: import unittest class Te ...

  8. python unittest+parameterized,单元测试框架+参数化

    总要写新的自动化测试模块,在这里把demo记录下来,后面方便自己直接复制粘贴 from nose_parameterized import parameterized import unittest ...

  9. SpringBoot使用MockMVC单元测试Controller

    对模块进行集成测试时,希望能够通过输入URL对Controller进行测试,如果通过启动服务器,建立http client进行测试,这样会使得测试变得很麻烦,比如,启动速度慢,测试验证不方便,依赖网络 ...

随机推荐

  1. 单片机pwm控制基本原理详解

    前言 PWM是Pulse Width Modulation的缩写,它的中文名字是脉冲宽度调制,一种说法是它利用微处理器的数字输出来对模拟电路进行控制的一种有效的技术,其实就是使用数字信号达到一个模拟信 ...

  2. javascript之奇淫技巧

    最近准备面试,复习一下javascript,整理了一些javascript的奇淫技巧~ //为兼容ie的模拟Object.keys() Object.showkeys = function(obj) ...

  3. Spring乱码问题解决方案

    请求乱码 GET请求乱码: 原因:请求参数带在url地址上.url地址什么时候解析? tomcat收到请求对url进行编解码(ISO8859-1) 解决方案:在tomcat的8080端口配置出加上 U ...

  4. Nlog 简单的快速攻略

    废话不多说直接进入正题. 1.在项目中加入Nlog的应用 安装后会出现两个文件 2.我们打开Nlog.config配置文件设置日志记录 <?xml version="1.0" ...

  5. laravel基于redis实现的一个简单的秒杀系统

    说明:网上很多redis秒杀系统的文章,看的都是一头雾水,然后自己来实现一个,也方便以后自己学习 实现的方式是用的redis的list队列,框架为laravel 核心部分为list的pop操作,此操作 ...

  6. 斯坦福大学公开课机器学习: advice for applying machine learning | deciding what to try next(revisited)(针对高偏差、高方差问题的解决方法以及隐藏层数的选择)

    针对高偏差.高方差问题的解决方法: 1.解决高方差问题的方案:增大训练样本量.缩小特征量.增大lambda值 2.解决高偏差问题的方案:增大特征量.增加多项式特征(比如x1*x2,x1的平方等等).减 ...

  7. HDU - 5952 Counting Cliques(DFS)

    A clique is a complete graph, in which there is an edge between every pair of the vertices. Given a ...

  8. (链表 set) leetcode 817. Linked List Components

    We are given head, the head node of a linked list containing unique integer values. We are also give ...

  9. 解析:为什么设计师选择mac电脑居多?

    mac电脑的使用者中程序员和设计师居多,上篇文章说明了程序员选择mac的原因以及使用体验,这次,本文说明一下,设计师选择mac的原因. 解析:为什么程序员应该有一台Mac个人电脑? 1.外观. 设计师 ...

  10. bzoj2333 离线 + 线段树

    https://www.lydsy.com/JudgeOnline/problem.php?id=2333 有N个节点,标号从1到N,这N个节点一开始相互不连通.第i个节点的初始权值为a[i],接下来 ...