【项目经验】Mockito教程
一、教程
转载:https://blog.csdn.net/sdyy321/article/details/38757135/
源码分析:https://www.cnblogs.com/dengshihuang/p/7903550.html
属性默认值:https://yanbin.blog/mockito-mocked-default-fields-method-returns/#more-8359
API文档:http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html
项目源码:https://github.com/mockito/mockito
使用案例:https://blog.csdn.net/Christopher36/article/details/81036683
首先添加maven依赖
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
当然mockito需要junit配合使用
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
然后为了使代码更简洁,最好在测试类中导入静态资源
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
下面我们开始使用mockito来做测试
package com.spring.sxf.mockito; import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.exceptions.verification.NoInteractionsWanted; import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List; import static org.mockito.Mockito.*;
import static org.junit.Assert.*; /**
* @author <a href="mailto:shangxiaofei@meituan.com">尚晓飞</a>
* @date 7:52 PM 2019/4/26
*/
public class MockitoTest { //验证要mock的对象,是否发生过某些行为
@Test
public void testArrayList() {
//生成mock对象
ArrayList<String> mockList = mock(ArrayList.class);
//使用mock的对象
mockList.add("SXF");
mockList.add("456"); //验证行为add("SXF"),add("123")是否发生过
verify(mockList).add("SXF");
verify(mockList).add("456");
} //模拟我们所期望的结果
@Test
public void testArrayList1() {
//生成mock对象
ArrayList<String> mockList = mock(ArrayList.class);
//
when(mockList.size()).thenReturn(2);
int size = mockList.size();
assertEquals(2, size); } //模拟我们期望的结果
@Test(expected = NullPointerException.class)
public void when_thenThrow() throws IOException {
OutputStream outputStream = mock(OutputStream.class);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
//预设当流关闭时抛出异常
doThrow(new IOException()).when(outputStream).close();
outputStream.close();
} //参数匹配
@Test
public void with_arguments() {
Comparable comparable = mock(Comparable.class);
//预设根据不同的参数返回不同的结果
when(comparable.compareTo("Test")).thenReturn(1);
when(comparable.compareTo("Omg")).thenReturn(2);
assertEquals(1, comparable.compareTo("Test"));
assertEquals(2, comparable.compareTo("Omg"));
//对于没有预设的情况会返回默认值
assertEquals(0, comparable.compareTo("Not stub"));
} //除了匹配制定参数外,还可以匹配自己想要的任意参数
@Test
public void with_unspecified_arguments() {
List list = mock(List.class);
//匹配任意参数
when(list.get(anyInt())).thenReturn(1);
when(list.contains(argThat(new IsValid()))).thenReturn(true);
assertEquals(1, list.get(1));
assertEquals(1, list.get(999));
assertTrue(list.contains(1));
assertTrue(!list.contains(3));
} private class IsValid extends ArgumentMatcher<List> {
@Override
public boolean matches(Object o) {
return (Integer) o == 1 || (Integer) o == 2;
}
} //需要注意的是如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配
@Test
public void all_arguments_provided_by_matchers() {
Comparator comparator = mock(Comparator.class);
comparator.compare("nihao", "hello");
//如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配
verify(comparator).compare(anyString(), eq("hello"));
//下面的为无效的参数匹配使用
//verify(comparator).compare(anyString(),"hello");
} //验证确切的调用次数
@Test
public void verifying_number_of_invocations() {
List list = mock(List.class);
list.add(1);
list.add(2);
list.add(2);
list.add(3);
list.add(3);
list.add(3);
//验证是否被调用一次,等效于下面的times(1)
verify(list).add(1);
verify(list, times(1)).add(1);
//验证是否被调用2次
verify(list, times(2)).add(2);
//验证是否被调用3次
verify(list, times(3)).add(3);
//验证是否从未被调用过
verify(list, never()).add(4);
//验证至少调用一次
verify(list, atLeastOnce()).add(1);
//验证至少调用2次
verify(list, atLeast(2)).add(2);
//验证至多调用3次
verify(list, atMost(3)).add(3); } //模拟方法体抛出异常
@Test(expected = RuntimeException.class)
public void doThrow_when() {
List list = mock(List.class);
doThrow(new Exception()).when(list).add(1);
list.add(1);
} //验证执行顺序
@Test
public void verification_in_order() {
List list = mock(List.class);
List list2 = mock(List.class);
list.add(1);
list2.add("hello");
list.add(2);
list2.add("world");
//将需要排序的mock对象放入InOrder
InOrder inOrder = inOrder(list, list2);
//下面的代码不能颠倒顺序,验证执行顺序
inOrder.verify(list).add(1);
inOrder.verify(list2).add("hello");
inOrder.verify(list).add(2);
inOrder.verify(list2).add("world");
} //确保模拟对象上无互动发生
@Test
public void verify_interaction(){
List list = mock(List.class);
List list2 = mock(List.class);
List list3 = mock(List.class);
list.add(1);
verify(list).add(1);
verify(list,never()).add(2);
//验证零互动行为
verifyZeroInteractions(list2,list3);
} //找出冗余的互动(即未被验证到的)
@Test(expected = NoInteractionsWanted.class)
public void find_redundant_interaction(){
List list = mock(List.class);
list.add(1);
list.add(2);
verify(list,times(2)).add(anyInt());
//检查是否有未被验证的互动行为,因为add(1)和add(2)都会被上面的anyInt()验证到,所以下面的代码会通过
verifyNoMoreInteractions(list); List list2 = mock(List.class);
list2.add(1);
list2.add(2);
verify(list2).add(1);
//检查是否有未被验证的互动行为,因为add(2)没有被验证,所以下面的代码会失败抛出异常
verifyNoMoreInteractions(list2);
} //9、使用注解来快速模拟
//在上面的测试中我们在每个测试方法里都mock了一个List对象,为了避免重复的mock,是测试类更具有可读性,我们可以使用下面的注解方式来快速模拟对象:
@Mock
private List mockList;
//构造方法
public MockitoTest(){
MockitoAnnotations.initMocks(this);
} @Test
public void shorthand(){
mockList.add(1);
verify(mockList).add(1);
} }
二、spring项目+单元测试使用mockito
一、单元测试类
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
public class RouteServiceTest { //要被mock的接口
@Mock
private IChannelQueueCountService iChannelQueueCountService; //使用了要被mock对象的类,需要注入mock对象
@InjectMocks
@Autowired
private ChannelChooseService channelChooseService; //发起调用的接口
@Autowired
private TRouteService.Iface tRouteService; //mock对象注入
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
} @Test
public void test01() throws TException { when(iChannelQueueCountService.getChannelQueueCounts(anyList(), anyLong(), anyBoolean())).thenAnswer(new Answer<Map<Integer, Integer>>() { @Override
public Map<Integer, Integer> answer(InvocationOnMock invocation) throws Throwable {
HashMap<Integer, Integer> map = new HashMap<>();
Object[] args = invocation.getArguments();
List<Integer> ids = (List<Integer>) args[0];
for (Integer id : ids) {
map.put(id, 1);
}
return map;
}
}); TChooseChannelReq tChooseChannelReq = new TChooseChannelReq(56789, 219, 999, 6000, "shangxiaofei", "6212260200052453285", TPPType.PRIVATE, 10, 34, 99999);
TChooseChannelRes res = tRouteService.chooseChannel(tChooseChannelReq);
System.out.println("接口调用返回:" + res.getLogicalChannelId()); }
}
【项目经验】Mockito教程的更多相关文章
- Mockito教程
Mockito教程 2017-01-20 目录 1 Mockito 介绍 1.1 Mockito是什么? 1.2 为什么需要Mock 1.3 Stub和Mock异同 1.4 Mockito资 ...
- 最近面试java后端开发的感受:如果就以平时项目经验来面试,通过估计很难——再论面试前的准备
在上周,我密集面试了若干位Java后端的候选人,工作经验在3到5年间.我的标准其实不复杂:第一能干活,第二Java基础要好,第三最好熟悉些分布式框架,我相信其它公司招初级开发时,应该也照着这个标准来面 ...
- 【建议收藏】缺少 Vue3 和 Spring Boot 的实战项目经验?我这儿有啊!
缺少 Vue3 和 Spring Boot 的实战项目经验?缺少学习项目和练手项目?我这儿有啊! 从 2019 年到 2021 年,空闲时间里陆陆续续做了一些开源项目,推荐给大家啊!记得点赞和收藏噢! ...
- 《项目经验》--通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来的Json数据写入数据库表中
先看一下我要实现的功能界面: 这个界面的功能在图中已有展现,课程分配(教师教授哪门课程)在之前的页面中已做好.这个页面主要实现的是授课,即给老师教授的课程分配学生.此页面实现功能的步骤已在页面 ...
- Java项目经验——程序员成长的关键(转载)
Java就是用来做项目的!Java的主要应用领域就是企业级的项目开发!要想从事企业级的项目开发,你必须掌握如下要点:1.掌握项目开发的基本步骤2.具备极强的面向对象的分析与设计技巧3.掌握用例驱动.以 ...
- Java项目经验
Java项目经验 转自CSDN. Java就是用来做项目的!Java的主要应用领域就是企业级的项目开发!要想从事企业级的项目开发,你必须掌握如下要点:1.掌握项目开发的基本步骤2.具备极强的面向对象的 ...
- OSG项目经验2<在场景中添加文字面版>
添加文字版需要用到osg的三个名字空间: osgText::Text,这个类用来添加文字和设置文字的一些属性: ...
- java程序员面试交流项目经验
粘贴自:https://blog.csdn.net/wangyuxuan_java/article/details/8778211 1:请你介绍一下你自己 这是面试官常问的问题.一般人回答这个问题过于 ...
- 新巴巴运动网上商城 项目 快速搭建 教程 The new babar sports online mall project quickly builds a tutorial
新巴巴运动网上商城 项目 快速搭建 教程 The new babar sports online mall project quickly builds a tutorial 作者:韩梦飞沙 Auth ...
- 项目经验分享[转自min.jiang]
最近三个月,我非常荣幸的做为TeamLeader带领几个小组成员做了一个国外项目,这里想为大家分享一些小经验,尽管我佣有六年多的项目经验,但我一直的方向是架构师.大家知道架构师一般情况是偏向技 ...
随机推荐
- @Autowired注解与@Qualifier注解搭配使用
问题:当一个接口实现由两个实现类时,只使用@Autowired注解,会报错,如下图所示 实现类1 实现类2 controller中注入 然后启动服务报错,如下所示: Exception encount ...
- 浅谈java 之 Map
先来一张Map的类继承图 Map :Hashtable .HashMap .LinkedHashMap .TreeMap 的比较 1.Hashtable的方法实现了synchronized 是线程 ...
- vivado封装IP
reference: https://www.cnblogs.com/mouou/p/5851736.html 1.新建一个测试工程 工程化的设计方法是离不开工程的,第一步往往都是新建工程,后面我 ...
- 对弈的C++学习笔记
2018-07-11上传 一:从C到C++ 1.C++新类型 bool 判断真假 占用一个字节 if(条件) 真1或者假 0 bool 类型的取值 true false ...
- bootstrap-fileinput视频上传
在页面编写一个input框: <input id="input-repl-3a" name="videoFileAddress" type="f ...
- 自学python之路(day1)
1. 下载和安装Pycharm文本编辑器,解释器Python3 2. 了解python2和python3的不同 如输出中文时,python2需要在代码前加 # -*- encoding:utf-8 - ...
- 18-09-15 潘一刘老师 讲课replace 控件输入函数检测的包
控件输入 指的是 一般金融机构 输入密码时候需要文本 键盘不能输入时候 用到的
- case 函数的简单使用记录下
Case有2中格式:简单Case函数和Case搜索函数. 简单函数:case sex when '1' then '男' when '2' then ‘女’ else '其它' end;(sex是列 ...
- 《贝贝GO》技术支持
贝贝GO是一个采用R2M模式的电子商务平台,通过零售商到制造商的两点直线连接,去除中间所有分销代理环节,结合互联网打造全新的线下新零售,旨在为用户提供高品质.高性价比商品的同事带动零售业的新发展.提升 ...
- python之99乘法表
#99乘法表 fir=1 while fir<=9: sec=1 while sec<=fir: print(str(fir)+'*'+str(sec)+'='+str(fir*sec)) ...