Mockito常用方法及示例

2024-02-12 19:32
文章标签 方法 常用 示例 mockito

本文主要是介绍Mockito常用方法及示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Mockit是一个开源mock框架,官网:http://mockito.org/,源码:https://github.com/mockito/mockito

要使用Mockit,首先需要在我们工程中引入对应的jar包,对于maven工程而言,需要添加如下依赖项即可:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <dependency>  
  2.     <groupId>org.mockito</groupId>  
  3.     <artifactId>mockito-core</artifactId>  
  4.     <version>2.0.5-beta</version>  
  5. </dependency>  
而在我们实际使用时,为了组织测试case的需要,我们可能还需要testng:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <dependency>  
  2.     <groupId>org.testng</groupId>  
  3.     <artifactId>testng</artifactId>  
  4.     <version>6.8.8</version>  
  5.     <scope>test</scope>  
  6. </dependency>  

在进行下面的mock test示例之前,我们先建两个简单的被测类Demo、ParameterClass。

Demo.java:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.anlegor.test;  
  2.   
  3. public class Demo {  
  4.   
  5.     private String name ="laowang";  
  6.     private int age;  
  7.   
  8.     public Demo(String name, int age) {  
  9.         this.name = name;  
  10.         this.age = age;  
  11.     }  
  12.   
  13.     public String speak(String str) {  
  14.         return str;  
  15.     }  
  16.     public String talk(String str)  
  17.     {  
  18.         return str;  
  19.     }  
  20.     public String methodNoParameters()  
  21.     {  
  22.         return name;  
  23.     }  
  24.   
  25.     public String methodCustomParameters(ParameterClass parameter,String str)  
  26.     {  
  27.         return str;  
  28.     }  
  29.   
  30.     public String methodHaveChildObj(ParameterClass parameter,String str)  
  31.     {  
  32.         parameter.childTalk(str);  
  33.         return str;  
  34.   
  35.     }  
  36. }  

ParameterClass.java

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.anlegor.test;  
  2.   
  3. public class ParameterClass {  
  4.   
  5.     public ParameterClass() {  
  6.   
  7.     }  
  8.   
  9.     public String childTalk(String str)  
  10.     {  
  11.         return str;  
  12.     }  
  13.   
  14. }  

我们在进行mock的时候,常见会有如下一些场景:

1、 构造无参函数的返回

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 测试无参数函数mock  
  3.  */  
  4. @Test(priority=0)  
  5. public void testReturnDirect()  
  6. {  
  7.     String mocked = "mocked Return";  
  8.     Demo demo  = Mockito.mock(Demo.class);  
  9.     Mockito.when(demo.methodNoParameters()).thenReturn(mocked);  
  10.     Assert.assertEquals(demo.methodNoParameters(), mocked);  
  11. }  

2、构造有基本类型作为参数的返回

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 测试任意基本类型参数函数mock  
  3.  */  
  4. @Test(priority=1)  
  5. public void testMethodWithParameter()  
  6. {  
  7.     String word"mocked Return";  
  8.     Demo demo =  Mockito.mock(Demo.class);  
  9.     Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word);  
  10.     Assert.assertEquals(demo.speak("你好"), word);  
  11. }  

3、构造有基本类型作为参数,但是只针对特定参数输入才mock返回值

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 测试特定参数mock  
  3.  */  
  4. @Test(priority=2)  
  5. public void testMethodWithSpecificParameter()  
  6. {  
  7.     String word"mocked Return";  
  8.     Demo demo =  Mockito.mock(Demo.class);  
  9.     Mockito.when(demo.speak(Mockito.matches(".*大爷$"))).thenReturn(word);  
  10.     Assert.assertEquals(demo.speak("隔壁李大爷"), word);  
  11. }  

4、构造自定义类作为函数参数的返回,这种情况稍微复杂一些,需要实现一个matcher类

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 测试自定义类型参数的mock  
  3.  */  
  4. @Test(priority=3)  
  5. public void testMethodWithCustomParameter()  
  6. {  
  7.     String word"mocked Return";  
  8.     Demo demo =  Mockito.mock(Demo.class);  
  9.     Mockito.when(demo.methodCustomParameters(Mockito.argThat(new IsParameterClass()),  
  10.             Mockito.anyString())).thenReturn(word);  
  11.     Assert.assertEquals(demo.methodCustomParameters(new ParameterClass(), "你猜"), word);  
  12. }  
  13. //自定义一个与之匹配的matcher类  
  14. class IsParameterClass extends ArgumentMatcher<ParameterClass> {  
  15.     public boolean matches(Object para) {  
  16.         return para.getClass() == ParameterClass.class;  
  17.     }  
  18.  }  

5、构造null返回

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 测试mock的函数返回null  
  3.  */  
  4. @Test(priority=4)  
  5. public void testMethodWithReturnNull()  
  6. {  
  7.     String word"mocked Return";  
  8.     Demo demo =  Mockito.mock(Demo.class);  
  9.     Mockito.when(demo.speak(Mockito.anyString())).thenReturn(null);  
  10.     Assert.assertNotEquals(demo.speak("你猜"), word);  
  11. }  

6、构造mock的函数抛出异常,当然我们可以在testng中设置expectedExceptions以显示声明会抛出指定类型的异常,这样该条case执行的时候就会成功

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 测试mock的函数抛出异常  
  3.  */  
  4. @Test(expectedExceptions=org.mockito.exceptions.base.MockitoException.class,priority=5)  
  5. public void testMethodReturnException()  
  6. {  
  7.     String word"mocked Return";  
  8.     Demo demo =  Mockito.mock(Demo.class);  
  9.     Mockito.when(demo.speak(Mockito.anyString())).thenThrow(new Exception());  
  10.     demo.speak("你猜");  
  11. }  

7、某些反复调用,我们希望对于每次调用都返回不同的mock值

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 测试mock的不同次调用返回不同的值  
  3.  */  
  4. @Test(priority=6)  
  5. public void testMethodMultiDiffReturn()  
  6. {  
  7.     String word"mocked Return 0";  
  8.     String word1"mocked Return 1";  
  9.     Demo demo =  Mockito.mock(Demo.class);  
  10.     Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word).thenReturn(word1);  
  11.     Assert.assertEquals(demo.speak("你猜"), word);  
  12.     Assert.assertEquals(demo.speak("你猜"), word1);  
  13. }  

8、验证函数执行是否经过了mock

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 验证方法是否被mock且是否为所执行的参数调用  
  3.  */  
  4. @Test(expectedExceptionsorg.mockito.exceptions.misusing.NotAMockException.class,priority=7)  
  5. public void testMockedMethodRun()  
  6. {  
  7.     String word"mocked Return";  
  8.     Demo demo =  Mockito.mock(Demo.class);  
  9.     Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word);  
  10.     Assert.assertEquals(demo.speak("你猜"), word);  
  11.     Mockito.verify(demo.speak("你猜"));  
  12.     //下面这个参数的方法调用并没有被执行过,所以会抛出NotAMockException的异常  
  13.     Mockito.verify(demo.speak("nicai"));  
  14. }  

如果对于上面的反复使用Mockito.when***的写法很厌烦的话,就直接静态导入org.mockito.Mockito.*即可。

当然,mockito的作用也不仅仅如上面,更详细的使用可以 参考它很详细的帮助文档:

http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html

这篇关于Mockito常用方法及示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/703408

相关文章

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e

Python中logging模块用法示例总结

《Python中logging模块用法示例总结》在Python中logging模块是一个强大的日志记录工具,它允许用户将程序运行期间产生的日志信息输出到控制台或者写入到文件中,:本文主要介绍Pyt... 目录前言一. 基本使用1. 五种日志等级2.  设置报告等级3. 自定义格式4. C语言风格的格式化方法

Spring 中的切面与事务结合使用完整示例

《Spring中的切面与事务结合使用完整示例》本文给大家介绍Spring中的切面与事务结合使用完整示例,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录 一、前置知识:Spring AOP 与 事务的关系 事务本质上就是一个“切面”二、核心组件三、完

JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法

《JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法》:本文主要介绍JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法,每种方法结合实例代码给大家介绍的非常... 目录引言:为什么"相等"判断如此重要?方法1:使用some()+includes()(适合小数组)方法2

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

QT Creator配置Kit的实现示例

《QTCreator配置Kit的实现示例》本文主要介绍了使用Qt5.12.12与VS2022时,因MSVC编译器版本不匹配及WindowsSDK缺失导致配置错误的问题解决,感兴趣的可以了解一下... 目录0、背景:qt5.12.12+vs2022一、症状:二、原因:(可以跳过,直奔后面的解决方法)三、解决方