Mocking Super Class Method Invocations with PowerMock

Mocking Superclass Method Invocations with PowerMock

Code Example

See the setup page to learn more about setting up PowerMock.

There may be situations when you are forced to call a super class method when overriding. For instance, in Android development, one must constantly interact with the life cycle call back methods. However, when running unit tests on these methods, exceptions are thrown due to Android system dependency interactions in super class method calls (unit tests are run locally on the developer's machine). Therefore, mocking the super class method invocations are crucial towards running successful unit tests.

SuperClass.java
1|    package main;
2|    public class SuperClass {
3|        public void foo() {
4|            System.out.println("Super Class!");
5|        }
6|    }
ChildClass.java
1|    package main;
2|    public class ChildClass extends SuperClass {
3|        @Override
4|        public void foo() {
5|            super.foo();
6|            System.out.println("Child Class!");
7|        }
8|    }
SuperClassMockTest.java
1 |      package test;
2 |
3 |      import main.ChildClass;
4 |
5 |      import org.junit.Test;
6 |      import org.junit.runner.RunWith;
7 |      import org.powermock.core.classloader.annotations.PrepareForTest;
8 |      import org.powermock.modules.junit4.PowerMockRunner;
9 |
10|     @PrepareForTest(ChildClass.class)
11|     @RunWith(PowerMockRunner.class)
12|     public class SuperClassMockTest {
13|         @Test
14|         public void onlyPrintChildClassTest() {
15|             // Setup
16|             ChildClass classUnderTest = new ChildClass();
17|             PowerMockito.suppress(PowerMockito.
18|             methods(SuperClass.class, "foo"));
19|    
20|             // Test
21|             classUnderTest.foo();
22|         }
23|     }
Console Output:
Child Class!

As expected, the "Super Class!" String was not printed due to super.foo() being mocked by PowerMockito.suppress(PowerMockito.methods(SuperClass.class, "foo")). Another important thing to take note of is the @PrepareForTest() annotation. As with many other PowerMock method calls, the class under test needs to be included in order for the mocking to work correctly.

Comments

Popular posts from this blog

Verifying Static Method Calls

Unit Testing a Singleton Using PowerMock