springboot利用mock进行junit单元测试,测试controller
2024-10-19 14:51:19
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 因示例项目代码较多没法上传,需要源码请留言
最新文章
- 锋利的jquery学习笔记
- ADB调试桥安装(方式一)
- Ajax--跨域访问的三种方法
- Qt 智能指针学习(7种指针)
- Android下 scrollview的滚动停止事件的监听方法
- win7本地搭建git ssh服务器
- eclipse自动生成的appcompat_v7出错
- Mac 安装Rudy环境 pod安装前的准备工作
- Android 7.0 调取系统相机崩溃解决android.os.FileUriExposedException
- Redis入门学习
- 【剑指offer】扑克牌的顺子
- springtest-junit-jidi--测试接口
- sql server 任务调度与CPU
- C#工具:WPF生成图片验证码
- ES(Elasticsearch)
- One VS Rest
- CentOS6.8下安装memcached并设置开机自启动
- 好用的js模板
- Apache通过配置.htaccess文件禁止访问.git、.svn等目录
- C# Contains 包含空字符串的问题
热门文章
- selenium+python处理Alert弹窗
- 『Python』matplotlib实现GUI效果
- 『GoLang』fmt包的使用
- 剑指offer计划27(栈与队列困难)---java
- python OSError: [Errno 22] Invalid argument: &#39;\u202aF://text
- 实验2:Open vSwitch虚拟交换机实践
- 调试器地址出现大小端紊乱,引发的异常: 0xC0000005: 读取位置 0xFFFFFFFFFFFFFFFF 时发生访问冲突。
- The Data Way Vol.3|做到最后只能删库跑路?DBA 能做的还有很多
- 题解 [BJOI2019]奥术神杖
- 常用的SQL查询思维/场景