Mocking Static class methods

In Mockito we cannot mock static class methods, so we can use PowerMock which extends the Mockito features and provides its own features. One of which is mocking static class methods.

Below code will give an example how to mock static class methods

Calculator


package package1;

public class Calculator {
    public static int add(int value1, int value2) {
        return value1 + value2;
    }
}

Main Test Code


package package1;

import static org.junit.Assert.*;
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(Calculator.class)
public class CalculatorTest {
    @Before
    public void setUp() {
        PowerMockito.mockStatic(Calculator.class);
    }
    
    @Test
    public void testAdd() {
        Mockito.when(Calculator.add(anyInt(), anyInt())).thenReturn(5);
        assertEquals(5, Calculator.add(1, 2));
    }
}

Explanation

As shown in the above code. We have created a static Calculator class with one static method ‘add’. In the test code we marked the test class with @RunWith annotation indicating the JUnit to use PowerMockRunner runner class to execute the test class.

Then we use PowerMock’s @PrepareForTest annotation telling the mock framework to manipulate mentioned class at byte level.

By calling PowerMockito.mockStatic in the setUp method, we tell the framework to create a mock of the class. The framework creates the mock and adds it to the internal repository, so that the test methods can use it.

Then we use the mock object similar to the way other mock objects created by Mockito are used.

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