Posts

Showing posts with the label JUnit

PowerMock Static Spy

This post shows how to partially mock a class's static methods. 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("UnderTest!"); 7| MockClass.foo2(); 8| } 9| } MockClass.java 1 | package main; 2 | 4 | public class MockClass { 5 | public static void foo() { 6 | System.out.println("Mocked Method!"); 7 | } 9 | 10| public static void foo2() { 11| System.out.println("foo2!"); 12| } 13| } StaticSpyTest.java 1 | package test; 2 | import main.*; 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.powermock.api.mockito.PowerMockito; 6 | import org.powermock.core.classloader.annotations.PrepareForTest; 7 | import org.p...

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) 1...

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()...