整个项目结构:

定义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. MOSFET的半桥驱动电路设计要领详解

    1 引言 MOSFET凭开关速度快.导通电阻低等优点在开关电源及电机驱动等应用中得到了广泛应用.要想使MOSFET在应用中充分发挥其性能,就必须设计一个适合应用的最优驱动电路和参数.在应用中MOSFE ...

  2. 牛客小白月赛12J(序列自动机)

    题目链接:https://ac.nowcoder.com/acm/contest/392/J 题目大意:给一个字符串s,然后在给出n个其他的字符串,判断每个字符串是否为s的子序列. 例: 输入: no ...

  3. JavaScript FormData的详细介绍及使用

    本文转自:https://blog.csdn.net/liupeifeng3514/article/details/78988001 FormData的详细介绍及使用请点击此处,那里对FormData ...

  4. 团体程序设计天梯赛(CCCC) L3013 非常弹的球 不同思路

    团体程序设计天梯赛代码.体现代码技巧,比赛技巧.  https://github.com/congmingyige/cccc_code

  5. Day20--Python--约束和异常处理

    1. 异常处理(处理异常,抛出异常,自定义异常) 异常: 程序运行过程中产生的错误 1. 产生异常. raise 异常类(), 抛出异常 2. 处理异常: try: xxxxxxxx # 尝试执行的代 ...

  6. node.js(小案例)_使用mongodb对学生信息列表优化

    一.前言 1.这篇文章主要对上一篇案列在操作增删改的时候使用mongodb进行优化 2.项目源码(包含上):https://github.com/4561231/crud-express-node.g ...

  7. vue实现购物车和地址选配(二)

    参考文献: vue官网: vue.js 效果展示:全选和取消全选,计算总金额 项目源代码:https://github.com/4561231/hello_world 项目核心代码实现及踩坑 1.全选 ...

  8. php-resque 轻量级队列

    一:简介 github地址:https://github.com/chrisboulton/php-resque 这个轻量级队列是由 Ruby 开发的 Resque 启发而来的. 注意:1. php- ...

  9. 5.django学习模型

    ##Django Models ##编写models 1.在应用根目录下创建models.py并引入models模块,创建类,继承models.Model该类即是一张数据表 2.字段创建 ##映射数据 ...

  10. SQL Server索引的作用

    一.深入浅出理解索引结构 实际上,您可以把索引理解为一种特殊的目录.微软的SQL SERVER提供了两种索引:聚集索引(clustered index,也称聚类索引.簇集索引)和非聚集索引(noncl ...