A good developer always writes a unit test case for his/her code. While writing test cases, we came across various types of scenarios, including the one where we need to mock static methods. One of the common examples of such scenario is where our service is using some static methods from a third party library.
Here, one way to deal is to have an adapter around which can provide isolation during testing which can be easily mocked using Mockito. But, if we don’t go with writing the adapters for this, then we can go with PowerMock.
PowerMock is a framework that extends other mock libraries giving them more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.
To use PowerMock, we need to include the following libraries:
<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.6.2</version> <scope>test</scope> </dependency>
<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.6.2</version> <scope>test</scope> </dependency>
The latest version can be found at https://mvnrepository.com/artifact/org.powermock
To understand its functionality, let’s go through an example:
We have a class by the name DemoUtil which includes a static method by the name demoStaticMethod.
Here is our class DemoImpl for using the static method from Demo class:
Now, we will write our test cases:
The above example demonstrates a way to mock a static method. PowerMock can do much more, we just need to explore it.
I hope this blog will help you to use PowerMock for mocking static methods.