Stubbing final methods

This post explains how to stub a final method.

The class to be tested is as shown below

Class1

package package5;

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

The test class is as shown below

Test Class

1  package package5;
2  
3  import org.junit.Before;
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  import org.mockito.Mockito;
10 
11 import static org.mockito.Matchers.*;
12 import static org.junit.Assert.*;
13 
14 @RunWith(PowerMockRunner.class)
15 @PrepareForTest(Class1.class)
16 public class Class1Test {
17  private Class1 class1;
18  
19  @Before
20  public void setUp() {
21      class1 = PowerMockito.mock(Class1.class);
22  }
23 
24  @Test
25  public void testMethod1() {
26      PowerMockito.when(class1.method1(anyInt())).thenReturn(1);
27      
28      assertEquals(2, class1.method1(2));
29  }
30 }

Explanation

At line 14, we instruct the junit runner to use.

At line 15, we indicate the class which has to prepared for testing which in this case is Class1

At line 21, we create a mock of the class

At line 26, we instruct the PowerMockito to return 1 whenever class1 method1 is called with any int value.

In this way we can stub the final method.

Leave a Reply