整个项目结构:

定义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. 使用item pipeline处理保存数据

    一个Item Pipeline 不需要继承特定基类,只需要实现某些特定方法,面向接口. class MyPipeline(object): def __init__(self): "&quo ...

  2. 数组拆分I

    题目描述 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最 ...

  3. centos7系统安装完成后一些基本的优化

    安装完centos7.3后,做一些基本的操作 基本操作一:主机名 centos7有一个新的修改主机名的命令hostnamectl # hostnamectl set-hostname --static ...

  4. Gym - 100989F

    You must have heard about Agent Mahone! Dr. Ibrahim hired him to catch the cheaters in the Algorithm ...

  5. golang go语言通道类型的通道示例 通道的通道

    几点注意:go的无缓存通道 通道make 创建后,即使里面是空的,也可以取里面内容.但是程序会被阻塞. 通道的规则是没人取,是不能往里面放的.放的线程会阻塞. 最外层的requestChan相当于一个 ...

  6. 洛谷P3709 大爷的字符串

    题意:多次求区间众数的出现次数. 解: 这题居然可以莫队...... 首先开个桶.然后还要开个数组,cnt[i]表示出现i次的数有多少个. 然后就可以O(1)修改了. #include <cst ...

  7. (转)你应该知道的RPC原理

    背景:对于项目中的RPC框架,仅仅停留在使用层面,对于其底层的实现原理不是很清楚.这样的后果是很危险的,对于面试官来说,跟不知道这个东西一样. 转载自:https://www.cnblogs.com/ ...

  8. 【洛谷 P2430 严酷的训练】

    题目背景 Lj的朋友WKY是一名神奇的少年,在同龄人之中有着极高的地位... 题目描述 他的老师老王对他的程序水平赞叹不已,于是下决心培养这名小子. 老王的训练方式很奇怪,他会一口气让WKY做很多道题 ...

  9. C# winform TreeView中关于checkbox选择的完美类[转]

    http://www.cnblogs.com/kingangWang/archive/2011/08/15/2139119.html public static class TreeViewCheck ...

  10. python: 多态与虚函数;

    通过python的abc模块能够实现虚函数: 首先在开头from abc import   ABCMeta, abstractmethod 例子 : #!/usr/bin/python #coding ...