【转】Mockito教程

article/2025/10/8 21:12:15

原文地址:https://www.cnblogs.com/Ming8006/p/6297333.html

 

1 Mockito 介绍 [3]

1.1 Mockito是什么?

Mockito是mocking框架,它让你用简洁的API做测试。而且Mockito简单易学,它可读性强和验证语法简洁。

1.2 为什么需要Mock

测试驱动的开发( TDD)要求我们先写单元测试,再写实现代码。在写单元测试的过程中,我们往往会遇到要测试的类有很多依赖,这些依赖的类/对象/资源又有别的依赖,从而形成一个大的依赖树,要在单元测试的环境中完整地构建这样的依赖,是一件很困难的事情。如下图所示: 

为了测试类A,我们需要Mock B类和C类(用虚拟对象来代替)如下图所示:

1.3 Stub和Mock异同[1]

  • 相同:Stub和Mock都是模拟外部依赖
  • 不同:Stub是完全模拟一个外部依赖, 而Mock还可以用来判断测试通过还是失败 

1.4 Mockito资源

  • 官网: http://mockito.org
  • API文档:http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html
  • 项目源码:https://github.com/mockito/mockito 

1.5 使用场景

  • 提前创建测试; TDD(测试驱动开发)
  • 团队可以并行工作
  • 你可以创建一个验证或者演示程序
  • 为无法访问的资源编写测试
  • Mock 可以交给用户
  • 隔离系统  

2 使用Mockito [2][4]

添加maven依赖

      <dependency><groupId>org.mockito</groupId><artifactId>mockito-all</artifactId><version>1.9.5</version><scope>test</scope></dependency>

添加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.*;

2.1 验证行为

复制代码

    @Testpublic void verify_behaviour(){//模拟创建一个List对象List mock = mock(List.class);//使用mock的对象mock.add(1);mock.clear();//验证add(1)和clear()行为是否发生verify(mock).add(1);verify(mock).clear();}

复制代码

2.2 模拟我们所期望的结果

复制代码

    @Testpublic void when_thenReturn(){//mock一个Iterator类Iterator iterator = mock(Iterator.class);//预设当iterator调用next()时第一次返回hello,第n次都返回worldwhen(iterator.next()).thenReturn("hello").thenReturn("world");//使用mock的对象String result = iterator.next() + " " + iterator.next() + " " + iterator.next();//验证结果assertEquals("hello world world",result);}

复制代码

复制代码

    @Test(expected = IOException.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();}

复制代码

2.3 RETURNS_SMART_NULLS和RETURNS_DEEP_STUBS

RETURNS_SMART_NULLS实现了Answer接口的对象,它是创建mock对象时的一个可选参数,mock(Class,Answer)。

在创建mock对象时,有的方法我们没有进行stubbing,所以调用时会放回Null这样在进行操作是很可能抛出NullPointerException。如果通过RETURNS_SMART_NULLS参数创建的mock对象在没有调用stubbed方法时会返回SmartNull。例如:返回类型是String,会返回"";是int,会返回0;是List,会返回空的List。另外,在控制台窗口中可以看到SmartNull的友好提示。

复制代码

    @Testpublic void returnsSmartNullsTest() {List mock = mock(List.class, RETURNS_SMART_NULLS);System.out.println(mock.get(0));//使用RETURNS_SMART_NULLS参数创建的mock对象,不会抛出NullPointerException异常。另外控制台窗口会提示信息“SmartNull returned by unstubbed get() method on mock”System.out.println(mock.toArray().length);}

复制代码

RETURNS_DEEP_STUBS也是创建mock对象时的备选参数

RETURNS_DEEP_STUBS参数程序会自动进行mock所需的对象,方法deepstubsTest和deepstubsTest2是等价的

复制代码

    @Testpublic void deepstubsTest(){Account account=mock(Account.class,RETURNS_DEEP_STUBS);when(account.getRailwayTicket().getDestination()).thenReturn("Beijing");account.getRailwayTicket().getDestination();verify(account.getRailwayTicket()).getDestination();assertEquals("Beijing",account.getRailwayTicket().getDestination());}@Testpublic void deepstubsTest2(){Account account=mock(Account.class); RailwayTicket railwayTicket=mock(RailwayTicket.class);        when(account.getRailwayTicket()).thenReturn(railwayTicket); when(railwayTicket.getDestination()).thenReturn("Beijing");account.getRailwayTicket().getDestination();verify(account.getRailwayTicket()).getDestination();    assertEquals("Beijing",account.getRailwayTicket().getDestination());}    public class RailwayTicket{private String destination;public String getDestination() {return destination;}public void setDestination(String destination) {this.destination = destination;}        }public class Account{private RailwayTicket railwayTicket;public RailwayTicket getRailwayTicket() {return railwayTicket;}public void setRailwayTicket(RailwayTicket railwayTicket) {this.railwayTicket = railwayTicket;}}

复制代码

2.4 模拟方法体抛出异常

    @Test(expected = RuntimeException.class)public void doThrow_when(){List list = mock(List.class);doThrow(new RuntimeException()).when(list).add(1);list.add(1);}

2.5 使用注解来快速模拟 

在上面的测试中我们在每个测试方法里都mock了一个List对象,为了避免重复的mock,是测试类更具有可读性,我们可以使用下面的注解方式来快速模拟对象:

    @Mockprivate List mockList;

OK,我们再用注解的mock对象试试 

    @Testpublic void shorthand(){mockList.add(1);verify(mockList).add(1);}

运行这个测试类你会发现报错了,mock的对象为NULL,为此我们必须在基类中添加初始化mock的代码

复制代码

public class MockitoExample2 {@Mockprivate List mockList;public MockitoExample2(){MockitoAnnotations.initMocks(this);}@Testpublic void shorthand(){mockList.add(1);verify(mockList).add(1);}
}

复制代码

或者使用built-in runner:MockitoJUnitRunner

复制代码

@RunWith(MockitoJUnitRunner.class)
public class MockitoExample2 {@Mockprivate List mockList;@Testpublic void shorthand(){mockList.add(1);verify(mockList).add(1);}
}

复制代码

2.6 参数匹配

复制代码

    @Testpublic 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"));}

复制代码

除了匹配制定参数外,还可以匹配自己想要的任意参数

复制代码

    @Testpublic 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>{@Overridepublic boolean matches(Object o) {return o == 1 || o == 2;}}

复制代码

注意:如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配,如下代码:

复制代码

    @Testpublic 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");}

复制代码

2.7 自定义参数匹配

复制代码

    @Testpublic void argumentMatchersTest(){//创建mock对象List<String> mock = mock(List.class);//argThat(Matches<T> matcher)方法用来应用自定义的规则,可以传入任何实现Matcher接口的实现类。when(mock.addAll(argThat(new IsListofTwoElements()))).thenReturn(true);mock.addAll(Arrays.asList("one","two","three"));//IsListofTwoElements用来匹配size为2的List,因为例子传入List为三个元素,所以此时将失败。verify(mock).addAll(argThat(new IsListofTwoElements()));}class IsListofTwoElements extends ArgumentMatcher<List>{public boolean matches(Object list){return((List)list).size()==2;}}

复制代码

2.8 捕获参数来进一步断言

较复杂的参数匹配器会降低代码的可读性,有些地方使用参数捕获器更加合适。

复制代码

        @Testpublic void capturing_args(){PersonDao personDao = mock(PersonDao.class);PersonService personService = new PersonService(personDao);ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);personService.update(1,"jack");verify(personDao).update(argument.capture());assertEquals(1,argument.getValue().getId());assertEquals("jack",argument.getValue().getName());}class Person{private int id;private String name;Person(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public String getName() {return name;}}interface PersonDao{public void update(Person person);}class PersonService{private PersonDao personDao;PersonService(PersonDao personDao) {this.personDao = personDao;}public void update(int id,String name){personDao.update(new Person(id,name));}}

复制代码

2.9 使用方法预期回调接口生成期望值(Answer结构)

复制代码

@Testpublic void answerTest(){when(mockList.get(anyInt())).thenAnswer(new CustomAnswer());assertEquals("hello world:0",mockList.get(0));assertEquals("hello world:999",mockList.get(999));}private class CustomAnswer implements Answer<String>{@Overridepublic String answer(InvocationOnMock invocation) throws Throwable {Object[] args = invocation.getArguments();return "hello world:"+args[0];}}

复制代码

也可使用匿名内部类实现

复制代码

    @Testpublic void answer_with_callback(){//使用Answer来生成我们我们期望的返回when(mockList.get(anyInt())).thenAnswer(new Answer<Object>() {@Overridepublic Object answer(InvocationOnMock invocation) throws Throwable {Object[] args = invocation.getArguments();return "hello world:"+args[0];}});assertEquals("hello world:0",mockList.get(0));assertEquals("hello world:999",mockList.get(999));}

复制代码

2.10 修改对未预设的调用返回默认期望

复制代码

    @Testpublic void unstubbed_invocations(){//mock对象使用Answer来对未预设的调用返回默认期望值List mock = mock(List.class,new Answer() {@Overridepublic Object answer(InvocationOnMock invocation) throws Throwable {return 999;}});//下面的get(1)没有预设,通常情况下会返回NULL,但是使用了Answer改变了默认期望值assertEquals(999, mock.get(1));//下面的size()没有预设,通常情况下会返回0,但是使用了Answer改变了默认期望值assertEquals(999,mock.size());}

复制代码

2.11 用spy监控真实对象  

  • Mock不是真实的对象,它只是用类型的class创建了一个虚拟对象,并可以设置对象行为
  • Spy是一个真实的对象,但它可以设置对象行为
  • InjectMocks创建这个类的对象并自动将标记@Mock、@Spy等注解的属性值注入到这个中

复制代码

    @Test(expected = IndexOutOfBoundsException.class)public void spy_on_real_objects(){List list = new LinkedList();List spy = spy(list);//下面预设的spy.get(0)会报错,因为会调用真实对象的get(0),所以会抛出越界异常//when(spy.get(0)).thenReturn(3);//使用doReturn-when可以避免when-thenReturn调用真实对象apidoReturn(999).when(spy).get(999);//预设size()期望值when(spy.size()).thenReturn(100);//调用真实对象的apispy.add(1);spy.add(2);assertEquals(100,spy.size());assertEquals(1,spy.get(0));assertEquals(2,spy.get(1));verify(spy).add(1);verify(spy).add(2);assertEquals(999,spy.get(999));spy.get(2);}

复制代码

2.12 真实的部分mock

复制代码

    @Testpublic void real_partial_mock(){//通过spy来调用真实的apiList list = spy(new ArrayList());assertEquals(0,list.size());A a  = mock(A.class);//通过thenCallRealMethod来调用真实的apiwhen(a.doSomething(anyInt())).thenCallRealMethod();assertEquals(999,a.doSomething(999));}class A{public int doSomething(int i){return i;}}

复制代码

2.13 重置mock

复制代码

    @Testpublic void reset_mock(){List list = mock(List.class);when(list.size()).thenReturn(10);list.add(1);assertEquals(10,list.size());//重置mock,清除所有的互动和预设reset(list);assertEquals(0,list.size());}

复制代码

2.14 验证确切的调用次数

复制代码

    @Testpublic 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);}

复制代码

2.15 连续调用

复制代码

    @Test(expected = RuntimeException.class)public void consecutive_calls(){//模拟连续调用返回期望值,如果分开,则只有最后一个有效when(mockList.get(0)).thenReturn(0);when(mockList.get(0)).thenReturn(1);when(mockList.get(0)).thenReturn(2);when(mockList.get(1)).thenReturn(0).thenReturn(1).thenThrow(new RuntimeException());assertEquals(2,mockList.get(0));assertEquals(2,mockList.get(0));assertEquals(0,mockList.get(1));assertEquals(1,mockList.get(1));//第三次或更多调用都会抛出异常mockList.get(1);}

复制代码

2.16 验证执行顺序

复制代码

    @Testpublic 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对象放入InOrderInOrder inOrder = inOrder(list,list2);//下面的代码不能颠倒顺序,验证执行顺序inOrder.verify(list).add(1);inOrder.verify(list2).add("hello");inOrder.verify(list).add(2);inOrder.verify(list2).add("world");}

复制代码

2.17 确保模拟对象上无互动发生

复制代码

    @Testpublic 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);}

复制代码

2.18 找出冗余的互动(即未被验证到的)

复制代码

    @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);}

复制代码

3 Mockito如何实现Mock[3]

 

Mockito并不是创建一个真实的对象,而是模拟这个对象,他用简单的when(mock.method(params)).thenRetrun(result)语句设置mock对象的行为,如下语句:

// 设置mock对象的行为 - 当调用其get方法获取第0个元素时,返回"first"
Mockito.when(mockedList.get(0)).thenReturn("first");

在Mock对象的时候,创建一个proxy对象,保存被调用的方法名(get),以及调用时候传递的参数(0),然后在调用thenReturn方法时再把“first”保存起来,这样,就有了构建一个stub方法所需的所有信息,构建一个stub。当get方法被调用的时候,实际上调用的是之前保存的proxy对象的get方法,返回之前保存的数据。

参考

[1] 单元测试之Stub和Mock

[2] mockito简单教程

[3] Mockito入门

[4] 学习Mockito


http://chatgpt.dhexx.cn/article/9nrbQxpb.shtml

相关文章

mockito使用教程

一、什么是 Mock 测试 Mock 测试就是在测试过程中&#xff0c;对于某些不容易构造&#xff08;如 HttpServletRequest 必须在Servlet 容器中才能构造出来&#xff09;或者不容易获取比较复杂的对象&#xff08;如 JDBC 中的ResultSet 对象&#xff09;&#xff0c;用一个虚拟的…

Mockito教程

目录 1 Mockito 介绍 1.1 Mockito是什么&#xff1f; 1.2 为什么需要Mock 1.3 Stub和Mock异同 1.4 Mockito资源 1.5 使用场景 2 使用Mockito 2.1 验证行为 2.2 模拟我们所期望的结果 2.3 RETURNS_SMART_NULLS和RETURNS_DEEP_STUBS 2.4 模拟方法体抛出异常 …

python的取整函数:向上取整,向下取整,四舍五入取整

#encoding:utf-8 import math#向上取整 print "math.ceil---" print "math.ceil(2.3) > ", math.ceil(2.3) print "math.ceil(2.6) > ", math.ceil(2.6)#向下取整 print "\nmath.floor---" print "math.floor(2.3) > &q…

[Python] Python数值取整

美图欣赏2022/06/22 1.向上取整math.ceil() 不论正负,所有小数都是向着数值更大的方向取整 import math math.ceil(-0.5) # 0 math.ceil(-0.9) # 0 math.ceil(0) # 0 math.ceil(0.5) # 1 math.ceil(1.2) # 2 2.向下取整math.floor() 不论正负,所有小数都是向着数值更小的方…

python的 取整 及 四舍五入方法(包含list元素取整)

目录 1、向下取整int()2、四舍五入round()2.1 表达式&#xff1a;2.2 注意&#xff1a;尽量不用round&#xff01;&#xff0c;原因如下 3、向上取整math.ceil()4、分别取整数部分和小数部分5、list元素取整 1、向下取整int() >>> a 3.75 >>> int(a) 32、四…

python中取整数操作

python中取整数操作 ★向靠近零的方向取整 int(x)内置函数【https://docs.python.org/zh-cn/3/library/functions.html#int 】&#xff0c;向靠近零的方向取整&#xff0c;x是数字表达式&#xff0c;如 int(4.4) #得到4 int(-4.4) #得到-4 int(4.5) #得到4 int(-4.5) …

python取整(不同方法的取整)

1. 向下取整 int是截断取整 举个例子 4.x等于4 2.四舍五入 round( )函数简介 菜鸟教程中介绍到&#xff0c;round() 函数作用就是&#xff0c;返回浮点数x的四舍五入值。 x round(5.76543, 2) print(x) >>> x5.773、向上取整 向上取整需要用到 math 模块中的 ce…

【Java之网络】网络基本概念总结

网络相关概念 一. 局域网和广域网1. 局域网&#xff08;LAN&#xff09;&#xff08;1&#xff09;定义&#xff08;2&#xff09;特点 2. 广域网&#xff08;WAN&#xff09;&#xff08;1&#xff09;定义&#xff08;2&#xff09;特点 二. IP地址和端口号1. IP地址2. 端口号…

java网络编程学习基础篇

一、基础背景 时代背景 自2000年左右&#xff0c;Web的快速发展以及2010左右的云原生和云计算的提出&#xff0c;网络通信的重要性越来越凸显出来&#xff1b; 对于用户来说&#xff1a;软件的响应速度和体验是越来越重要的&#xff0c;而网络通信是决定响应速度关键因素之一…

神经网络和CNN的一些基础概念,基础知识的梳理

&#xff08;好吧&#xff0c;这又是一篇软文&#xff0c;适合初学者&#xff09; 一、通用概念&#xff1a; 1. 有监督学习方法与非监督学习方法&#xff1a; 必须要有训练集与测试样本&#xff0c;模型在训练集中寻找规律&#xff0c;训练结束对测试样本使用这种规律进行…

一些神经网络基础知识归纳

神经网络&#xff08;NN&#xff09;复杂度 NN复杂度&#xff0c;多用NN层数和NN参数个数表示 如上图示 空间复杂度 层数隐藏层的层数1个输出层 上图为2层NN 总参数 3*44 4*2226 时间复杂度 乘加运算次数 3*44*220 指数衰减学习率 可以先用较大学习率&#xff0c;快速得…

Java网络编程(一)网络的基本认知

前言 这是一个信息化的时代&#xff0c;在生活中&#xff0c;网络通信无处不在。比如发送短信&#xff0c;邮件&#xff0c;视频通话等。 以邮件为例子&#xff1a; ① 收件人&#xff1a; 相当于网络编程的ip地址端口号&#xff0c;定位到某一个具体的地方&#xff01;只有找…

第四章 使用JAVA构建神经网络

• 构建一个神经网络 •激活函数 • Encog持久化 •在代码里使用Encog Analyst 这章将展示用Encog怎样构造前馈与简单递归神经网络,以及在最后部分怎样保存这些神经网络。创建神经网络类型使用BasicNetwork和BasicLayer这两个类&#xff0c;除了这两个类&#xff0c;还使用…

深入浅出讲解神经网络的种类及举例说明

本文收录于《深入浅出讲解自然语言处理》专栏&#xff0c;此专栏聚焦于自然语言处理领域的各大经典算法&#xff0c;将持续更新&#xff0c;欢迎大家订阅&#xff01;个人主页&#xff1a;有梦想的程序星空个人介绍&#xff1a;小编是人工智能领域硕士&#xff0c;全栈工程师&a…

Java网络基础知识

目录 一&#xff0c;计算机网络 1&#xff0c;概念 2&#xff0c;计算机网络的主要功能 3&#xff0c;计算机网络分类 二&#xff0c;网络通信协议及接口 1&#xff0c;网络通信协议 2&#xff0c;网络通信接口 3&#xff0c;通信协议分层思想 4&#xff0c;协议分类 …

神经网络可以用来分类吗,神经网络如何实现分类

怎么用spss神经网络来分类数据 。 用spss神经网络分类数据方法如下&#xff1a;神经网络算法能够通过大量的历史数据&#xff0c;逐步建立和完善输入变量到输出结果之间的发展路径&#xff0c;也就是神经网络&#xff0c;在这个神经网络中&#xff0c;每条神经的建立以及神经…

BP神经网络JAVA实现详解

注&#xff1a;本文手动搬家自我的新浪博客点击打开链接 从2016年3月份左右&#xff0c;我的毕业设计开题答辩时间正好是AlphaGo大战李世石之日。还记得当时答辩PPT最末引用的图片还是这张&#xff1a; 李世石大战Google的AlphaGo 不过当时答辩情况并不理想&#xff0c;答辩组老…

Java网络编程--网络基础

文章目录 网络协议常用网络协议族&#xff08;簇&#xff09;(protocol)端口&#xff08;port&#xff09;常见知名端口动态端口 IP地址IP地址分类IPv4的分类IPv6子网掩码 网络协议 是为计算机网络中进行数据交换而建立的规则、标准或约定的集合。为了使不同计算机厂家生产的计…

神经网络如何实现分类,神经网络基本概念

人工神经网络分类方法 从20世纪80年代末期&#xff0c;人工神经网络方法开始应用于遥感图像的自动分类。 目前&#xff0c;在遥感图像的自动分类方面&#xff0c;应用和研究比较多的人工神经网络方法主要有以下几种&#xff1a;&#xff08;1&#xff09;BP&#xff08;BackP…

神经网络如何进行分类

1.首先搞清楚什么是感知机 如上图所示&#xff0c;输入为向量&#xff0c;经线性变换&#xff0c;再通过激活函数得到输出&#xff0c;这样一个完整的结构成为感知机。感知机是人工神经网络的最小单元&#xff0c;本质上由一个仿射变换接一个非线性变换组成。 上图wxb属于仿射变…