PowerMock Static Mocking

Here is how to mock static method calls within unit tests using PowerMock.

Code Example

See PowerMock Setup page to learn how to get started with PowerMock.

UnderTest.java
1|    package main;
2|    
3|    public class UnderTest {
4|        public void foo() {
5|            MockClass.foo();
6|            System.out.println("Unmocked Method!");
7|        }
8|    }    
MockClass.java
1|    package main;
2|    
3|    public class MockClass {
4|        public static void foo() {
5|            System.out.println("Mocked Method!");
6|        }
7|    }
StaticMockTest.java
1 |    package test;
2 |    
3 |    import main.*;
4 |    import org.junit.Test;
5 |    import org.junit.runner.RunWith;
6 |    import org.powermock.api.mockito.PowerMockito;
7 |    import org.powermock.core.classloader.annotations.PrepareForTest;
8 |    import org.powermock.modules.junit4.PowerMockRunner;
9 |    
10|    @PrepareForTest(MockClass.class)
11|    @RunWith(PowerMockRunner.class)
12|    public class StaticMockTest {
13|        @Test
14|        public void mockFooTest() {
15|            // Setup
16|            UnderTest obj = new UnderTest();
17|            PowerMockito.mockStatic(MockClass.class);
18|         
19|            // Test
20|            obj.foo();
21|        }
22|    }
Console Output
Unmocked Method!

Before mocking, you need to include the class that will be mocked into the @PrepareForTest annotation, as shown on line 9 in StaticSpyTest.java. After the annotation, PowerMockito.mockStatic(MockClass.class) (Line 15) mocks all static methods within MockClass.java. As a result, the String "Mocked Method!" is not displayed, thus MockClass.foo() is not invoked. If there were additional methods and method calls to MockClass.java, they would also not be invoked since the entire class is a mock. To learn how to only mock specific methods within a class, see Static Spy.

Comments

Popular posts from this blog

Mocking Super Class Method Invocations with PowerMock

Verifying Static Method Calls

Unit Testing a Singleton Using PowerMock