PowerMock API extension for Mockito that enables mocking of static methods, constructors, final classes and methods, private methods, and advanced testing capabilities through bytecode manipulation and custom classloading
—
PowerMock extends Mockito's object mocking capabilities to handle final classes, final methods, and native methods that cannot be mocked with standard Mockito. This enables comprehensive testing of legacy code without requiring architectural changes.
Create mocks of classes that cannot be mocked with standard Mockito, including final classes and classes with final methods.
static <T> T mock(Class<T> type);Parameters:
type - The class to mock (can be final)Returns: Mock instance of the specified type
Usage Example:
@Test
@PrepareForTest(FinalClass.class)
public void testFinalClassMocking() {
FinalClass mock = mock(FinalClass.class);
when(mock.getValue()).thenReturn("mocked value");
String result = mock.getValue();
assertEquals("mocked value", result);
verify(mock).getValue();
}Create enhanced mocks with a custom default answer strategy for unstubbed method calls.
static <T> T mock(Class<T> classToMock, Answer defaultAnswer);Parameters:
classToMock - The class to mockdefaultAnswer - Default answer strategy for unstubbed methodsReturns: Mock instance with custom default behavior
Usage Example:
@Test
@PrepareForTest(ServiceClass.class)
public void testMockWithCustomAnswer() {
ServiceClass mock = mock(ServiceClass.class, RETURNS_SMART_NULLS);
// Only stub specific method
when(mock.getImportantValue()).thenReturn("important");
String important = mock.getImportantValue(); // Returns "important"
String other = mock.getOtherValue(); // Returns smart null
}Create enhanced mocks with advanced MockSettings configuration for specialized testing scenarios.
static <T> T mock(Class<T> classToMock, MockSettings mockSettings);Parameters:
classToMock - The class to mockmockSettings - Advanced mock configurationReturns: Mock instance configured with specified settings
Usage Example:
@Test
@PrepareForTest(ComplexService.class)
public void testMockWithSettings() {
ComplexService mock = mock(ComplexService.class,
withSettings()
.name("ComplexServiceMock")
.defaultAnswer(RETURNS_DEEP_STUBS)
.extraInterfaces(Serializable.class));
when(mock.getConfiguration().getProperty("key")).thenReturn("value");
String property = mock.getConfiguration().getProperty("key");
assertEquals("value", property);
}Spy on objects that are final or otherwise not "spyable" with standard Mockito, enabling partial mocking of real objects.
static <T> T spy(T object);Parameters:
object - The real object to spy on (can be final)Returns: Spy instance that delegates to the real object unless stubbed
Usage Example:
@Test
@PrepareForTest(FinalService.class)
public void testSpyOnFinalObject() {
FinalService realService = new FinalService();
FinalService spy = spy(realService);
// Stub one method, others call real implementation
when(spy.getValue()).thenReturn("spied value");
String value = spy.getValue(); // Returns "spied value"
String realResult = spy.calculateSomething(); // Calls real method
verify(spy).getValue();
verify(spy).calculateSomething();
}Enable spying on static methods of a class, allowing partial mocking of static behavior.
static <T> void spy(Class<T> type);Parameters:
type - The class to enable static spying forUsage Example:
@Test
@PrepareForTest(UtilityClass.class)
public void testSpyOnClass() {
spy(UtilityClass.class);
// Stub one static method, others call real implementation
when(UtilityClass.getValue()).thenReturn("spied static value");
String value = UtilityClass.getValue(); // Returns "spied static value"
int realResult = UtilityClass.calculate(5, 3); // Calls real method
verifyStatic(UtilityClass.class);
UtilityClass.getValue();
}@Test
@PrepareForTest(HttpURLConnection.class)
public void testFinalThirdPartyClass() {
HttpURLConnection connection = mock(HttpURLConnection.class);
when(connection.getResponseCode()).thenReturn(200);
when(connection.getInputStream()).thenReturn(new ByteArrayInputStream("response".getBytes()));
// Test code that uses the mocked connection
MyHttpClient client = new MyHttpClient();
String response = client.makeRequest(connection);
assertEquals("response", response);
verify(connection).getResponseCode();
}@Test
@PrepareForTest(LegacyService.class)
public void testPartialMocking() {
LegacyService service = new LegacyService();
LegacyService spy = spy(service);
// Mock only the problematic dependency method
when(spy.callExternalService()).thenReturn("mocked external response");
// Test the main business logic with mocked dependency
String result = spy.processData("input");
// Verify the external call was made but returned mocked value
verify(spy).callExternalService();
assertTrue(result.contains("mocked external response"));
}@Test
@PrepareForTest(SystemClass.class)
public void testNativeMethodMocking() {
SystemClass mock = mock(SystemClass.class);
// Mock native method that would normally fail in test environment
when(mock.nativeSystemCall()).thenReturn("mocked native result");
ApplicationService service = new ApplicationService(mock);
service.performSystemOperation();
verify(mock).nativeSystemCall();
}@PrepareForTest annotation@RunWith(PowerMockRunner.class) or equivalentInstall with Tessl CLI
npx tessl i tessl/maven-org-powermock--powermock-api-mockito