Mocking static methods with Mockito
Mocking static methods with Mockito can be a bit more challenging than mocking instance methods, because Mockito is designed to work with object-oriented code and static methods are not object-oriented. However, it is possible to mock static methods using the PowerMock extension for Mockito.
Here's an example of how to mock a static method with Mockito and PowerMock:
Let's say you have a class called "MathUtils" with a static method called "sum" that adds two numbers together:
public class MathUtils {
public static int sum(int a, int b) {
return a + b;
}
}
To mock this method using Mockito and PowerMock, you would need to do the following:
- Add the PowerMock and Mockito dependencies to your project:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
- Use the @RunWith(PowerMockRunner.class) annotation on your test class to enable PowerMock:
@RunWith(PowerMockRunner.class)
public class MathUtilsTest {
// test methods
}
- Use the @PrepareForTest annotation to tell PowerMock which classes to prepare for testing. In this case, we want to prepare the MathUtils class:
@PrepareForTest(MathUtils.class)
public class MathUtilsTest {
// test methods
}
- Use the PowerMockito.mockStatic() method to mock the static method. In this case, we want to mock the sum() method:
PowerMockito.mockStatic(MathUtils.class);
PowerMockito.when(MathUtils.sum(2, 3)).thenReturn(5);
- Call the method(s) you want to test and assert the expected results. In this case, we want to test the sum() method:
int result = MathUtils.sum(2, 3);
assertEquals(5, result);
Here's the full example:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.api.mockito.PowerMockito;
@RunWith(PowerMockRunner.class)
@PrepareForTest(MathUtils.class)
public class MathUtilsTest {
@Test
public void testSum() {
PowerMockito.mockStatic(MathUtils.class);
PowerMockito.when(MathUtils.sum(2, 3)).thenReturn(5);
int result = MathUtils.sum(2, 3);
assertEquals(5, result);
}
}
This example demonstrates how to use PowerMock to mock a static method with Mockito. By preparing the class for testing and using PowerMockito.mockStatic(), you can simulate the behavior of the static method and test your code in isolation. However, it's important to use this technique sparingly, as it can make your tests more complex and harder to maintain
Leave a Comment