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

相关文章

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四