1  spring-boot-starter-test内置mockito,添加pom依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

2 示例controller

package com.shangcg.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; /**
* @version v1.0
* @Description: junit和mock单元测试示例
* @Author: shangcg
* @Date: 2019/12/24
*/ @RestController
public class UnitDemoController { @RequestMapping(value = "/hello.json", method = RequestMethod.GET)
public String getListTag(HttpServletRequest request,
@RequestParam(value = "name", required = false, defaultValue = "0") String name) {
try {
return "hello :" + name;
} catch (Exception e) {
e.printStackTrace();
}
return "hello everyone !";
} @RequestMapping(value = "/save.json", method = RequestMethod.POST)
public String saveTag(HttpServletRequest request,
@RequestParam(value = "name", required = true) String name,
@RequestParam(value = "level", required = true) Integer level) {
try {
return "recive your param " + "name: " + name + " level: " + level;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

3 示例测试类

package com.shangcg.controller;

import static org.junit.Assert.*;
import org.junit.Assert;
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.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; /**
* @version v1.0
* @Description: TODO
* @Author: shangcg
* @Date: 2019/12/24
*/ @RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UnitDemoControllerTest { @Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc; @Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();//建议使用这种
} @Test //对get方法的测试
public void testGetListTag() throws Exception { MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/hello.json")
.contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8")
.param("name", "shangcg")
).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn(); String content = mvcResult.getResponse().getContentAsString();
Assert.assertEquals("hello :shangcg", content);
} @Test //对post测试
public void saveTag() throws Exception { MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/save.json")
.contentType(MediaType.APPLICATION_JSON)
.param("name", "shangcg")
.param("level", "1")
).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
Assert.assertEquals("recive your param name: shangcg level: 1", content);
}
}

4 返回结果

5 因示例项目代码较多没法上传,需要源码请留言

springboot利用mock进行junit单元测试,测试controller的更多相关文章

  1. Junit mockito 测试Controller层方法有Pageable异常

    1.问题 在使用MockMVC+Mockito模拟Service层返回的时候,当我们在Controller层中参数方法调用有Pageable对象的时候,我们会发现,我们没办法生成一个Pageable的 ...

  2. SpringBoot: 16.整合junit单元测试(转)

    1.创建maven项目,修改pom.xml文件 <!--springboot项目依赖的父项目--> <parent> <groupId>org.springfram ...

  3. java基础第11期——Stream流、方法引用、junit单元测试

    1.Stream流 Stream流与io流是不同的东西,用于解决集合类库已有的弊端, 1.1 获取Stream流: Collection集合的Stream方法,注意Map集合要经过转化 default ...

  4. Spring MVC如何测试Controller(使用springmvc mock测试)

    在springmvc中一般的测试用例都是测试service层,今天我来演示下如何使用springmvc mock直接测试controller层代码. 1.什么是mock测试? mock测试就是在测试过 ...

  5. spring boot(三)Junit 测试controller

    Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法 一.单元测试的目的 简单来说就是在我们增加或者改动一些代码以后对所有逻辑的一个检测,尤其是在我们后期 ...

  6. ssm controller层 junit单元测试

    原文链接:https://www.cnblogs.com/oucbl/p/5943743.html springmvc controller junit 测试 作者:blouc@qq.com本文为作者 ...

  7. springboot使用MockMvc测试controller

    通常,在我们平时开发项目时,如果想要输入URL对Controller进行测试,在代码编辑之后,需要重启服务器,建立http client进行测试.这样会使得测试变得很麻烦,比如,启动速度慢,测试验证不 ...

  8. spring && Cobertura && maven &&junit 单元测试以及测试覆盖率

    1. 目的:       junit 单元测试,Cobertura   测试覆盖率报告       项目目录结构          2. maven 配置     <project xmlns= ...

  9. mybatis-generator没有自动生成代码和Junit测试controller

    本来mybatis的generator想要自动生成增删改的,但是到后来语句就两个select,原因是数据中没有给字段加primary,就不会有删改增. 以及Controller的Junit测试 先导入 ...

随机推荐

  1. MyBatis-Plus代码生成器的使用

    1.MyBatis-Plus简介 ​ 在代码开发中,肯定会遇到代码中对应数据库表去编写实体类的工作,若数据库表数量多的情况下,编写Entity,属实是一件消耗时间,且并没有什么技术含量的事情,如何解决 ...

  2. P4922-[MtOI2018]崩坏3?非酋之战!【dp】

    正题 题目链接:https://www.luogu.com.cn/problem/P4922 题目大意 题目好长直接放了 在崩坏 3 中有一个叫做天命基地的地方,女武神们将在基地中开派对与敌人们厮杀. ...

  3. Go变量与基础数据类型

    一.基础介绍 Go 是静态(编译型)语言,是区别于解释型语言的弱类型语言(静态:类型固定,强类型:不同类型不允许直接运算) 例如 python 就是动态强类型语言 1.Go 的特性: 跨平台的编译型语 ...

  4. centos7.5离线安装Docker及容器运行报OCI runtime create failed 问题定位与解决

    前言 接上篇 <记一次centos挂载ceph存储的坑> 服务器重做了centos7.5版本的操作系统,剩下就是安装docker,考虑yum安装耗时较长,我一般都是直接安装二进制版本doc ...

  5. Redis高可用解决方案:哨兵(Sentinel)

    哨兵是Redis的高可用解决方案:由多个哨兵组成的系统监视主从服务器,可以将下线的主服务器属下的某个从服 务器升级为新的主服务器,继续保障运行. 启动并初始化Sentinel redis-sentin ...

  6. Blazor Webassembly多标签页开发

    最近准备用Blazor Webassembly做后台开发要用到多标签页,找了半天发现绝大多数都是Blazor Server的多标签没有Webassembly.没办法只能自己想办法造轮子了. 查了许多资 ...

  7. 初探webpack之从零搭建Vue开发环境

    初探webpack之搭建Vue开发环境 平时我们可以用vue-cli很方便地搭建Vue的开发环境,vue-cli确实是个好东西,让我们不需要关心webpack等一些繁杂的配置,然后直接开始写业务代码, ...

  8. Postman实现SHA256withRSA签名

    @ 目录 获取pmlib 引入依赖bundle.js,有以下两种方式: 使用Pre-request Script对请求进行加签(具体加签字段请看自己项目) 获取pmlib 引入依赖bundle.js, ...

  9. 《看漫画学Pyhton》中计算水仙花数

    利用while循环实现 i = 100 r = 0 s = 0 t = 0 while i < 1000: r = i // 100 s = (i - r * 100) // 10 t = i ...

  10. for...of 和 for...in 是否可以直接遍历对象,有什么解决方案

    答案: for...of不能直接遍历对象,for  in可以直接遍历对象 原因: for...of需要实现iterator接口,对象没有实现iterator接口 解决: const obj = {a: ...