整个项目结构:

定义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. QBXT Day2主要是数据结构(没写完先占坑)

    简单数据结构 本节课可能用到的一些复杂度: O(log n). 1/1+1/1/.....1/N+O(n log n) 在我们初学OI的时候,总会遇到这么一道题. 给出N次操作,每次加入一个数,或者询 ...

  2. Spring cloud config 使用gitHub或者gitee连接

    1. 创建SpringCloud项目,引入对应的Spring-config-server对应的jar <dependency> <groupId>org.springframe ...

  3. Python3 与 C# 基础语法对比(Function专栏)

      Code:https://github.com/lotapp/BaseCode 多图旧版:https://www.cnblogs.com/dunitian/p/9186561.html 在线编程: ...

  4. Ubuntu下安装Flask虚拟环境及使用

    一.关于Flask介绍 诞生时间:Flask诞生于2010年,是Armin ronacher(人名)用 Python 语言基于 Werkzeug工具箱编写的轻量级Web开发框架. Flask框架包含两 ...

  5. POJ 1639 Picnic Planning 最小k度生成树

    Picnic Planning Time Limit: 5000MS   Memory Limit: 10000K Total Submissions:11615   Accepted: 4172 D ...

  6. socket编程 ------ UDP服务器

    void vLANcommunication( void *pvParameters ) { int32 listenfd; do{ listenfd = socket(AF_INET, SOCK_D ...

  7. 数据库连接池 C3p0

    数据库连接池 C3po 1 定义 本质上是个容器(集合) 存放数据库的连接容器(connection 对象) ,当系统初始化以后 容器就会创建 容器中就会申请一些连接对象 ,当用户来访问数据库的时候 ...

  8. C++: 带参数回调函数和不带参数的回调函数;

    在C++中,回调函数的应用比较广泛且重要. 通过传递函数指针到其他地方,能够实现远程回调的作用,能够实现远程调用而不需要事件触发信号或者其他机制来实现,方便而快捷: 首先,回调函数有两种形式:  静态 ...

  9. NoSQL数据库Mongodb副本集架构(Replica Set)高可用部署

    NoSQL数据库Mongodb副本集架构(Replica Set)高可用部署 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. MongoDB 是一个基于分布式文件存储的数据库.由 C ...

  10. linux shell变量的截取

    变量的截断,经常用到的是${},##和%%几个特殊符号.假设我们定义了一个变量为:file=/dir1/dir2/dir3/my.file.txt ,可以用${ }分别替换得到不同的值: ${file ...