Verify static method was called with PowerMock
This post is part of PowerMock series examples. The code shown in examples below is available in GitHub java-samples/junit repository.
In Mock static methods in JUnit with PowerMock example post, I have given information about PowerMock and how to mock a static method. In the current post, I will demonstrate how to verify given static method was called during execution of a unit test.
Example class for unit test
We are going to unit test a class called LocatorService that internally uses a static method from utility class Utils. Method randomDistance(int distance) in Utils is returning random variable, hence it has no predictable behavior and the only way to test it is by mocking it:public class LocatorService {
public Point generatePointWithinDistance(Point point, int distance) {
return new Point(point.getX() + Utils.randomDistance(distance),
point.getY() + Utils.randomDistance(distance));
}
}
And Utils class is:
import java.util.Random;
public final class Utils {
private static final Random RAND = new Random();
private Utils() {
// Utilities class
}
public static int randomDistance(int distance) {
return RAND.nextInt(distance + distance) - distance;
}
}
Nota bene: it is good code design practice to make utility classes final and with a private constructor.
Verify static method call
This is the full code. Additional details are shown below it.package com.automationrhapsody.junit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.verification.VerificationModeFactory;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class LocatorServiceTest {
private LocatorService locatorServiceUnderTest;
@Before
public void setUp() {
PowerMockito.mockStatic(Utils.class);
locatorServiceUnderTest = new LocatorService();
}
@Test
public void testStaticMethodCall() {
locatorServiceUnderTest
.generatePointWithinDistance(new Point(11, 11), 1);
locatorServiceUnderTest
.generatePointWithinDistance(new Point(11, 11), 234);
PowerMockito.verifyStatic(VerificationModeFactory.times(2));
Utils.randomDistance(1);
PowerMockito.verifyStatic(VerificationModeFactory.times(2));
Utils.randomDistance(234);
PowerMockito.verifyNoMoreInteractions(Utils.class);
}
}