Mocking final methods

This post will explain how to mock public final methods of a class using Powermock. Lets consider a class named “Class1” with the structure as shown below

Class to be tested


package package2;

public class Class1 {
    public final int method1(int value) {
        return value * value;
    }
}

Now we have to mock the final method, which is as shown below

Test Class


package package2;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyInt;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Class1.class)
public class Class1Test {
    
    private Class1 class1;
    
    @Before
    public void setUp() {
        class1 = PowerMockito.mock(Class1.class);
    }
    
    @Test
    public void testMethod1() {
        Mockito.when(class1.method1(anyInt())).thenReturn(5);
        assertEquals(5, class1.method1(5));
    }
}

Explanation

As shown in the above code we annotate the test class with @RunWith(PowerMockRunner.class) to indicate the JUnit to use PowerMockRunner to execute the test class. We tell the Powermock to prepare the class to be tested by adding annotation @PrepareForTest.

Then we create a mock object of the class in the setUp method and assign the mock object to the test class instance variable for future reference.

Then we mock the method as shown in the testMethod1 method.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s