Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use PowerMock to Mock static functions

Shulou Source: shulou.com Published: 2022-06-02 18:25:37 10月07日 Update

This article mainly introduces how to use PowerMock to Mock static functions, the article is very detailed, has a certain reference value, interested friends must read it!

Frameworks such as EasyMock and Mockito can not be mock for static, final and private methods. These frameworks generally implement mock by creating Proxy. PowerMock is a mock that uses CGLib to manipulate bytecode, so it can implement mock for the above methods. Let's start with a simple example today:

* the annotation is the specified Runner

The second is the class you want to test, which calls the static class

Let me give a simple example in conjunction with EasyMock:

Java code

Import java.io.IOException; public class SystemPropertyMockDemo {public String getSystemProperty () throws IOException {return System.getProperty ("property");}}

Java code

Import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner @ RunWith (PowerMockRunner.class) @ PrepareForTest ({SystemPropertyMockDemo.class}) public class SystemPropertyMockDemoTest {@ Test public void demoOfFinalSystemClassMocking () throws Exception {PowerMock.mockStatic (System.class); EasyMock.expect (System.getProperty ("property")) .andReturn ("my property"); PowerMock.replayAll () Assert.assertEquals ("my property", new SystemPropertyMockDemo (). GetSystemProperty ()); PowerMock.verifyAll ();}}

The PrepareForTest annotation is added to the test case to indicate the class to be tested, which contains calls to static methods.

Then specify the static class to test and its methods in the test class.

In fact, PowerMock is an extension to EasyMock, which is written in the same way as EasyMock.

Write such a simple example today, and then write down everything you use later.

Of course, you can refer to more:

Http://code.google.com/p/powermock/

In addition, its maven dependency is as follows, which I made a mistake when I used it.

Xml code

Org.powermockgroupId > powermock-module-junit4artifactId > 1.4.8version > testscope > dependency > org.powermockgroupId > powermock-api-easymockartifactId > 1.4.8version > testscope > dependency > the above is all the contents of the article "how to use PowerMock to Mock static functions". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Static tests methods code examples functions content more frameworks comments articles references same value interest writing bytes actually guys Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Tech Info Linux Microsoft Apple