Mockito单元测试实战
最近使用Mockito完成了几个简单的测试,写个博客mark一下:
第一种模拟web请求
@SpringBootTest
@RunWith(SpringRunner.class)
@WebAppConfiguration //测试环境使用,用来表示测试环境使用的ApplicationContext将是WebApplicationContext类型的;value指定web应用的根
public class ControllerTest {
private static final Logger logger = LogManager.getLogger(ControllerTest.class); @Autowired
private WebApplicationContext context; @Mock
private UserInfoService userInfoService; private MockMvc mockMvc; /**
* 构造MockMvc
* @throws Exception
*/
@Before
public void setupMockMvc() throws Exception {
// 初始化Mock
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
} /**
* 模拟add请求
*/
@Test
public void insertUserInfoTest() {
UserInfo userInfo = initUserInfo();
when(userInfoService.insert(any())).thenReturn(1);
logger.info("++++++++++++++++++++++++++" + userInfo.toString());
// 调用接口,传入添加的用户参数
try{
String response = mockMvc.perform(post("/userInfo/add").contentType(MediaType.APPLICATION_JSON)
.content(userInfo.toString()).header("SESSIONNO", "EA60F3C2C7384DBA8A7B8B114474DC12"))
.andReturn().getResponse().getContentAsString();
logger.info("******************" + response); }catch (Exception e) {
e.printStackTrace();
} } @Test
public void addTest() {
try {
// 1. controller mvc test
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/userInfo/add"))
.andExpect(MockMvcResultMatchers.handler().handlerType(UserInfoController.class))
.andExpect(MockMvcResultMatchers.handler().methodName("addUserInfo"))
// .andExpect(MockMvcResultMatchers.view().name("demo/hello"))
// .andExpect(MockMvcResultMatchers.model().attributeExists("msg"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
// Assert.assertNotNull(result.getModelAndView().getModel().get("msg")); }catch (Exception e) {
e.printStackTrace();
}
} /**
* 模拟update测试
*/
@Test
public void updateUserInfo() {
try{
// String response = mockMvc.perform(post("/user/updateUser").contentType(MediaType.APPLICATION_JSON)
// .content(userInfo.toString()).header("SESSIONNO", "EA60F3C2C7384DBA8A7B8B114474DC12"))
// .andReturn().getResponse().getContentAsString();
// logger.info("update****" + response);
}catch (Exception e) {
e.printStackTrace();
}
} private UserInfo initUserInfo() {
UserInfo userInfo = new UserInfo();
userInfo.setBirthday(new Timestamp(System.currentTimeMillis()));
userInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
userInfo.setEducation(5);
userInfo.setIdCardCode("********************");
userInfo.setMaritalStatus(1);
userInfo.setNickName("社会主义接班人");
userInfo.setPassword(encoderByMd5("a123456"));
userInfo.setPhoneNumber("************");
userInfo.setSex(1);
userInfo.setStatus(1);
userInfo.setUserAddress("hlxj");
userInfo.setUserEmail("**********@qq.com");
userInfo.setUserImage("图片");
userInfo.setUserName("dsc"); return userInfo;
} private String encoderByMd5(String password) {
//确定计算方法
String md5Password = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64en = new BASE64Encoder();
//加密后的字符串
md5Password = base64en.encode(md5.digest(password.getBytes("utf-8")));
logger.info(md5Password);
}catch (Exception e){
e.printStackTrace();
} return md5Password;
}
}
第二种模拟web请求
@RunWith(SpringRunner.class)
public class ServiceTest { private static final Logger logger = LogManager.getLogger(ServiceTest.class); @InjectMocks
UserInfoController userInfoController; @Mock
UserInfoService userInfoService; @Before
public void init() {
UserInfo userInfo = initUserInfo(); given(userInfoService.insert(any())).willReturn(1);
given(userInfoService.selectUnique(any())).willReturn(null, userInfo); } @Test
public void testAdd() {
UserInfo userInfo = new UserInfo();
userInfoController.addUserInfo(userInfo);
userInfo = initUserInfo();
userInfoController.addUserInfo(userInfo); } @Test
public void getUserInfoTest() {
UserInfo userInfo = new UserInfo();
logger.info("测试1*** " + userInfoController.getUserInfo(userInfo));
userInfo.setId(3L);
logger.info("测试2*** " + userInfoController.getUserInfo(userInfo));
} private UserInfo initUserInfo() {
UserInfo userInfo = new UserInfo();
userInfo.setBirthday(new Timestamp(System.currentTimeMillis()));
userInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
userInfo.setEducation(5);
userInfo.setIdCardCode("********************");
userInfo.setMaritalStatus(1);
userInfo.setNickName("社会主义接班人");
userInfo.setPassword(encoderByMd5("a123456"));
userInfo.setPhoneNumber("************");
userInfo.setSex(1);
userInfo.setStatus(1);
userInfo.setUserAddress("hlxj");
userInfo.setUserEmail("**********@qq.com");
userInfo.setUserImage("图片");
userInfo.setUserName("dsc"); return userInfo;
} private String encoderByMd5(String password) {
//确定计算方法
String md5Password = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64en = new BASE64Encoder();
//加密后的字符串
md5Password = base64en.encode(md5.digest(password.getBytes("utf-8")));
logger.info(md5Password);
}catch (Exception e){
e.printStackTrace();
} return md5Password;
}
}
以上两种只是我的个人测试,由于刚刚开始试验,对于一些细节还不是熟悉,期待日后修改。。。
Mockito单元测试实战的更多相关文章
- SpringBootTest单元测试实战、SpringBoot测试进阶高级篇之MockMvc讲解
1.@SpringBootTest单元测试实战 简介:讲解SpringBoot的单元测试 1.引入相关依赖 <!--springboot程序测试依赖,如果是自动创建项目默认添加--> &l ...
- 小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_17、SpringBootTest单元测试实战
笔记 1.@SpringBootTest单元测试实战 简介:讲解SpringBoot的单元测试 1.引入相关依赖 <!--springboot程 ...
- JUnit + Mockito 单元测试
原 JUnit + Mockito 单元测试(二) 2015年01月05日 17:26:02 sp42a 阅读数:60755 版权声明:本文为博主原创文章,未经博主允许不得转载. https://bl ...
- JUnit + Mockito 单元测试(二)
摘自: http://blog.csdn.net/zhangxin09/article/details/42422643 版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[-] 入门 ...
- 使用 Mockito 单元测试 – 教程
tanyuanji@126.com 版本历史 - - - - 使用 Mockito 进行测试 该教程主要讲解 Mockito 框架在Eclipse IDE 中的使用 目录 tanyuanji@12 ...
- JUnit + Mockito 单元测试(二)(good)
import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import java.util.Lis ...
- Mockito单元测试
Mockito简介 Mockito是一个单元测试框架,需要Junit的支持.在我们的项目中,都存在相当多的依赖关系,当我们在测试某一个业务相关的接口或则方法时,绝大多数时候是没有办法或则很难去添加所有 ...
- 基于spring与mockito单元测试Mock对象注入
转载:http://www.blogjava.net/qileilove/archive/2014/03/07/410713.html 1.关键词 单元测试.spring.mockito 2.概述 单 ...
- 一文让你快速上手 Mockito 单元测试框架
前言 在计算机编程中,单元测试是一种软件测试方法,通过该方法可以测试源代码的各个单元功能是否适合使用.为代码编写单元测试有很多好处,包括可以及早的发现代码错误,促进更改,简化集成,方便代码重构以及许多 ...
随机推荐
- table切换jquery插件 jQuery插件写法模板 流程
通过$.extend()来扩展jQuery 通过$.fn 向jQuery添加新的方法 通过$.widget()应用jQuery UI的部件工厂方式创建 通过$.extend()来扩展jQuery $. ...
- 最完整的dos命令字典,IIS服务命令,FTP命令
https://www.cnblogs.com/accumulater/p/10670051.html(优秀博文) 一.最完整的dos命令字典net use ipipc$ " " ...
- phpstorm对laravel的一些使用技巧
安装laravel插件,设置ctrl+alt+s 二 安装智能提示插件 composer require barryvdh/laravel-ide-helper 在config/app.php的pro ...
- Oracle做insert或者update时未提交事务导致表锁定解决办法
//查看被锁定表有几个 select object_name,machine,s.sid,s.serial# from v$locked_object l,dba_objects o ,v$sessi ...
- if的{}的省略
if (表达式) 语句; else if(表达式) 语句; else if(表达式) 语句; else 语句; 对应: if (表达式) { 语句1; 语句2; 语句N;//多个语句组成代码块 } e ...
- 跑的飞快的dinic
orz kczno1 目前还是不知道怎么卡,也不会证明复杂度是正确的 其实我感觉卡不了
- gcc各个版本下载
http://www.gnu.org/order/ftp.html http://ftp.gnu.org/gnu/gcc/
- 关于UTF-8和GBK编码的转换
$oldname=mb_convert_encoding($_POST['oldname'], "GBK" , "UTF-8");//将变量转码为GBK,已知原 ...
- hadoop解决Could not locate executable null\bin\winutils.exe in the Hadoop binaries.问题
先看下自己的JAVA_HOME里面有没有空格目录,如果有的话,先把JAVA_HOME换个没空格的位置. 在windows系统本地运行spark的wordcount程序,会出现一个异常,但不影响现有程序 ...
- NOIP-无线网路发射器选址
题目描述 随着智能手机的日益普及,人们对无线网的需求日益增大.某城市决定对城市内的公共场所覆盖无线网. 假设该城市的布局为由严格平行的129条东西向街道和129条南北向街道所形成的网格状,并且相邻的平 ...