mockito 静态方法

Mockito allows us to create mock objects. Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.

Mockito允许我们创建模拟对象。 由于静态方法属于该类,因此Mockito中无法模拟静态方法。 但是,我们可以结合使用PowerMock和Mockito框架来模拟静态方法。

使用PowerMock的Mockito Mock静态方法 (Mockito Mock Static Method using PowerMock)

PowerMock provides different modules to extend Mockito framework and run JUnit and TestNG test cases.

PowerMock提供了不同的模块来扩展Mockito框架并运行JUnit和TestNG测试用例。

Note that PowerMock doesn’t support JUnit 5 yet, so we will create JUnit 4 test cases. We will also learn how to integrate TestNG with Mockito and PowerMock.

请注意,PowerMock还不支持JUnit 5 ,因此我们将创建JUnit 4测试用例。 我们还将学习如何将TestNG与Mockito和PowerMock集成。

PowerMock依赖项 (PowerMock Dependencies)

We need following PowerMock dependencies for mocking static methods in Mockito.

我们需要遵循PowerMock依赖关系才能在Mockito中模拟静态方法。

  • powermock-api-mockito2: This is the core PowerMock dependency and used to extend Mockito2 mocking framework. If you are using Mockito 1.x versions then use powermock-api-mockito module.powermock-api-mockito2 :这是PowerMock的核心依赖项,用于扩展Mockito2模拟框架。 如果您使用的是Mockito 1.x版本,请使用powermock-api-mockito模块。
  • powermock-module-junit4: For running JUnit 4 test cases using PowerMock.powermock-module-junit4 :用于使用PowerMock运行JUnit 4测试用例。
  • powermock-module-testng: For running TestNG test cases and supporting PowerMock.powermock-module-testng :用于运行TestNG测试用例并支持PowerMock。

Below is the final pom.xml from our project.

以下是我们项目中的最终pom.xml。

<project xmlns="https://maven.apache.org/POM/4.0.0"xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.journaldev.powermock</groupId><artifactId>PowerMock-Examples</artifactId><version>0.0.1-SNAPSHOT</version><properties><testng.version>6.14.3</testng.version><junit4.version>4.12</junit4.version><mockito-core.version>2.19.0</mockito-core.version><powermock.version>2.0.0-beta.5</powermock.version><java.version>10</java.version></properties><dependencies><!-- TestNG --><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>${testng.version}</version><scope>test</scope></dependency><!-- JUnit 4 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit4.version}</version><scope>test</scope></dependency><!-- Mockito 2 --><dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>${mockito-core.version}</version><scope>test</scope></dependency><!-- PowerMock TestNG Module --><dependency><groupId>org.powermock</groupId><artifactId>powermock-module-testng</artifactId><version>${powermock.version}</version><scope>test</scope></dependency><!-- PowerMock JUnit 4.4+ Module --><dependency><groupId>org.powermock</groupId><artifactId>powermock-module-junit4</artifactId><version>${powermock.version}</version><scope>test</scope></dependency><!-- PowerMock Mockito2 API --><dependency><groupId>org.powermock</groupId><artifactId>powermock-api-mockito2</artifactId><version>${powermock.version}</version><scope>test</scope></dependency></dependencies><build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.7.0</version><configuration><source>${java.version}</source><target>${java.version}</target></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>2.22.0</version><dependencies><dependency><groupId>org.apache.maven.surefire</groupId><artifactId>surefire-junit47</artifactId><version>2.22.0</version></dependency><dependency><groupId>org.apache.maven.surefire</groupId><artifactId>surefire-testng</artifactId><version>2.22.0</version></dependency></dependencies><configuration><additionalClasspathElements><additionalClasspathElement>src/test/java/</additionalClasspathElement></additionalClasspathElements><!-- TestNG Test Fails when executed from command line with message"Cannot use a threadCount parameter less than 1" Works when threadCount is explicitly specified https://gist.github.com/juherr/6eb3e93e2db33979b7e90b63ddadc888--><threadCount>5</threadCount></configuration></plugin></plugins></build>
</project>

Note that I am using 2.0.0-beta.5 version of PowerMock. This version supports Java 10, however, it’s still in beta so there might be some issues present in complex cases.

请注意我正在使用2.0.0-beta.5版本的PowerMock。 该版本支持Java 10,但是它仍处于beta版本,因此在复杂情况下可能会出现一些问题。

When I tried to use current stable version 1.7.x, I got the following errors.

当我尝试使用当前稳定的版本1.7.x ,出现以下错误。

java.lang.NoSuchMethodError: org.mockito.internal.handler.MockHandlerFactory.createMockHandler(Lorg/mockito/mock/MockCreationSettings;)Lorg/mockito/internal/InternalMockHandler;at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:114)at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:73)

Here are GitHub issues opened for this exception – issue1 and issue2.

下面是打开了这个异常GitHub的问题- issue1和issue2 。

Let’s create a simple class with a static method.

让我们用静态方法创建一个简单的类。

package com.journaldev.mockito.staticmethod;public class Utils {public static boolean print(String msg) {System.out.println("Printing "+msg);return true;}
}

JUnit Mockito PowerMock示例 (JUnit Mockito PowerMock Example)

We need to do the following to integrate PowerMock with Mockito and JUnit 4.

我们需要执行以下操作以将PowerMock与Mockito和JUnit 4集成。

  • Annotate test class with @RunWith(PowerMockRunner.class) annotation.使用@RunWith(PowerMockRunner.class)批注注释测试类。
  • Annotate test class with @PrepareForTest and provide classed to be mocked using PowerMock.使用@PrepareForTest注释测试类,并提供使用PowerMock @PrepareForTest分类。
  • Use PowerMockito.mockStatic() for mocking class with static methods.使用PowerMockito.mockStatic()通过静态方法模拟类。
  • Use PowerMockito.verifyStatic() for verifying mocked methods using Mockito.使用PowerMockito.verifyStatic()来验证使用Mockito的模拟方法。

Here is a complete example of mocking static method using Mockito and PowerMock in JUnit test case.

这是在JUnit测试案例中使用Mockito和PowerMock模拟静态方法的完整示例。

package com.journaldev.mockito.staticmethod;import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.when;import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class JUnit4PowerMockitoStaticTest{@Testpublic void test_static_mock_methods() {PowerMockito.mockStatic(Utils.class);when(Utils.print("Hello")).thenReturn(true);when(Utils.print("Wrong Message")).thenReturn(false);assertTrue(Utils.print("Hello"));assertFalse(Utils.print("Wrong Message"));PowerMockito.verifyStatic(Utils.class, atLeast(2));Utils.print(anyString());}
}

TestNG Mockito PowerMock示例 (TestNG Mockito PowerMock Example)

For TestNG test cases, we don’t need to use @RunWith annotation. We need test classes to extend PowerMockTestCase so that PowerMockObjectFactory is used to create test class instance.

对于TestNG测试用例,我们不需要使用@RunWith批注。 我们需要测试类来扩展PowerMockTestCase以便使用PowerMockObjectFactory创建测试类实例。

package com.journaldev.mockito.staticmethod;import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;import static org.mockito.Mockito.*;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.Test;@PrepareForTest(Utils.class)
public class TestNGPowerMockitoStaticTest extends PowerMockTestCase{@Testpublic void test_static_mock_methods() {PowerMockito.mockStatic(Utils.class);when(Utils.print("Hello")).thenReturn(true);when(Utils.print("Wrong Message")).thenReturn(false);assertTrue(Utils.print("Hello"));assertFalse(Utils.print("Wrong Message"));PowerMockito.verifyStatic(Utils.class);Utils.print("Hello");PowerMockito.verifyStatic(Utils.class, times(2));Utils.print(anyString());}
}

摘要 (Summary)

PowerMock provides extended features for Mockito, one of them is the ability to test static methods. It’s easily integrated with JUnit 4 and TestNG. However, there is no near-term support plan for JUnit 5.

PowerMock为Mockito提供了扩展功能,其中之一就是能够测试静态方法。 它很容易与JUnit 4和TestNG集成。 但是,没有针对JUnit 5的近期支持计划。

GitHub Repository.GitHub Repository下载完整的项目。

翻译自: https://www.journaldev.com/21912/mockito-mock-static-method-powermock

mockito 静态方法

mockito 静态方法_Mockito模拟静态方法– PowerMock相关推荐

  1. mockito无效_Mockito模拟无效方法

    mockito无效 Most of the times Mockito when() method is good enough to mock an object's behavior. But w ...

  2. 静态路由_在Android中模拟静态方法:让我们总结一下

    静态路由 在Android中编写本地单元测试时,面临的局限性之一是测试是针对没有任何代码的android.jar版本运行的. 如文档所述,必须模拟对Android代码的任何依赖关系. 一个简单的单元测 ...

  3. 使用PowerMock模拟静态方法

    在最近的博客中,我试图强调使用依赖注入的好处,并表达一种想法,即这种技术的主要好处之一是,通过在类之间提供高度的隔离,它可以使您更轻松地测试代码,并且得出的结论是,许多好的测试等于好的代码. 但是,当 ...

  4. Mockito中模拟静态方法

    Mockito中模拟静态方法 背景 在项目实际开发中,编写单元测试用例时,需要对静态方法进行模拟,本次文章就简单整理下如何使用Mockito来模拟静态方法. 添加依赖 <dependency&g ...

  5. mockito入门_Mockito入门

    mockito入门 本文是我们名为" 用Mockito测试 "的学院课程的一部分. 在本课程中,您将深入了解Mockito的魔力. 您将了解有关"模拟",&qu ...

  6. mockito教程_Mockito教程

    mockito教程 Mockito is a java based mocking framework, used in conjunction with other testing framewor ...

  7. C#静态类 静态方法与非静态方法比较

    静态类 在类(class)上加入static修饰,表示该类无法被实例化,并将该类中,无法实例化变量或函数 静态类的主要特性 仅包含静态成员 无法实例化 静态类的本质,时一个抽象的密封类,所以不能被继承 ...

  8. java中synchronized修饰静态方法和非静态方法有什么区别?

    Synchronized修饰非静态方法 Synchronized修饰非静态方法,实际上是对调用该方法的对象加锁,俗称"对象锁". Java中每个对象都有一个锁,并且是唯一的.假设分 ...

  9. 使用synchronized修饰静态方法和非静态方法有什么区别

    前言 最近被问到了这个问题,第一次回答的也是很不好,在此参考网上答案进行整理记录.供大家学习参考. Synchronized修饰非静态方法 Synchronized修饰非静态方法,实际上是对调用该方法 ...

最新文章

  1. 太酷了,Python 制作足球可视化图表 | 代码干货
  2. 【.Net MF网络开发板研究-01】IP地址设定及简单web演示
  3. Qt-qwidget项目入门实例
  4. 剖析数组名、函数名(不是指针常量,更不是指针)
  5. 把一个数据库的数据插入到另外一个数据库
  6. 通过CentOS克隆虚拟机后发现无法启动网卡或无法上网的解决办法
  7. url解码java_JAVA对URL的解码【转】
  8. 天猫浏览型应用的CDN静态化架构演变
  9. 关于web中的自适应布局
  10. 简易电影售票系统(附部分总结)
  11. 【Java】URL下载网络资源(CloudMusic)
  12. ctype-Python的外部函数库(一)(摘抄Python官方文档)
  13. 使用命令修改dns服务器地址,Windows下使用命令行设置ip地址的DNS服务器
  14. SICP 习题2.61~2.62 排序表示的adjoin和union-set函数
  15. 十三年来,淘宝走过的大数据之路
  16. 磁盘管理压缩卷显示服务器异常,Win7分配盘符提示“磁盘管理控制台不是最新状态”错误怎么办...
  17. 可视化利器Tensorboard
  18. 慢慢整理一下用到的游戏相关工具
  19. 搜狗输入法自定义短语使用小技巧
  20. Altera PDN 设计和 FPGA 收发器性能

热门文章

  1. Oracle 11g完全卸载(Windows)
  2. WAP开发资料站(最新更新)
  3. [转载] python中callable_Python callable() 函数
  4. mysql 权限管理 记录
  5. python3-day2(基本回顾)
  6. PowerDesigner实用技巧小结(4)
  7. Windows7查看无线网络密码
  8. freemarker处理嵌套属性是否为空的判断
  9. PyTorch 入坑五 autograd与逻辑回归
  10. tensorflow随笔——concat(), stack(), unstack()