PowerMock API for Mockito 2.+ that enables advanced mocking of static methods, constructors, final classes and private methods through bytecode manipulation.
—
PowerMock's expectation setup system provides fluent interfaces for configuring mock behavior on private methods, constructors, and static methods. This comprehensive framework allows precise control over mock responses and argument matching.
Set up expectations for private method calls using method names and arguments.
public static <T> OngoingStubbing<T> when(Object instance, String methodName, Object... arguments) throws Exception;Configure expectations for private methods by specifying the method name and expected arguments.
Parameters:
instance - The object instance containing the private methodmethodName - Name of the private method to expectarguments - Expected arguments for the method callReturns:
OngoingStubbing<T> - Standard Mockito stubbing interface for configuring return valuesUsage Example:
UserService userService = spy(new UserService());
// Setup expectation for private method
when(userService, "validatePassword", "admin123").thenReturn(true);
when(userService, "validatePassword", "wrong").thenReturn(false);
// Execute code that calls private methods
boolean result1 = userService.authenticate("admin", "admin123");
boolean result2 = userService.authenticate("admin", "wrong");
assertTrue(result1);
assertFalse(result2);Set up expectations using Method objects for precise method identification.
public static <T> WithOrWithoutExpectedArguments<T> when(Object instance, Method method);Parameters:
instance - The object instancemethod - Method object obtained via reflectionReturns:
WithOrWithoutExpectedArguments<T> - Fluent interface for argument specificationUsage Example:
UserService service = spy(new UserService());
Method privateMethod = PowerMockito.method(UserService.class, "encryptData", String.class);
when(service, privateMethod)
.withArguments("sensitive")
.thenReturn("encrypted_sensitive");Configure expectations for static private methods.
public static <T> WithOrWithoutExpectedArguments<T> when(Class<?> cls, Method method);Usage Example:
Method staticPrivateMethod = PowerMockito.method(CryptoUtils.class, "generateKey", int.class);
when(CryptoUtils.class, staticPrivateMethod)
.withArguments(256)
.thenReturn("generated_key");Set up expectations without specifying method names, relying on argument type matching.
public static <T> OngoingStubbing<T> when(Object instance, Object... arguments) throws Exception;PowerMock attempts to find the private method based on the provided argument types.
Usage Example:
Calculator calc = spy(new Calculator());
// PowerMock finds private method based on argument types
when(calc, 10, 5).thenReturn(15); // matches private method(int, int)
when(calc, "operation").thenReturn("completed"); // matches private method(String)Configure expectations for static private methods using method names.
public static <T> OngoingStubbing<T> when(Class<?> clazz, String methodToExpect, Object... arguments) throws Exception;
public static <T> OngoingStubbing<T> when(Class<?> klass, Object... arguments) throws Exception;Usage Examples:
// By method name
when(SecurityUtils.class, "hashPassword", "secret").thenReturn("hashed_secret");
// By argument types
when(MathUtils.class, 42.0, 2).thenReturn(84.0);Set up expectations for constructor calls using Constructor objects.
public static <T> WithOrWithoutExpectedArguments<T> whenNew(Constructor<T> ctor);Parameters:
ctor - Constructor object to configure expectations forUsage Example:
Constructor<DatabaseConnection> constructor = DatabaseConnection.class.getConstructor(String.class, int.class);
DatabaseConnection mockConnection = mock(DatabaseConnection.class);
whenNew(constructor)
.withArguments("localhost", 5432)
.thenReturn(mockConnection);
// Code that creates new DatabaseConnection("localhost", 5432) will receive mockConnectionConfigure constructor expectations using class types.
public static <T> ConstructorExpectationSetup<T> whenNew(Class<T> type);Parameters:
type - Class whose constructor should be mockedReturns:
ConstructorExpectationSetup<T> - Fluent interface for constructor argument specificationUsage Example:
FileProcessor mockProcessor = mock(FileProcessor.class);
whenNew(FileProcessor.class)
.withArguments("/tmp/data.txt")
.thenReturn(mockProcessor);
// Any new FileProcessor("/tmp/data.txt") will return mockProcessorHandle expectations for private member classes, local classes, or anonymous classes.
public static <T> ConstructorExpectationSetup<T> whenNew(String fullyQualifiedName) throws Exception;Parameters:
fullyQualifiedName - Fully qualified name of the inner/local/anonymous classUsage Example:
// Mock inner class constructor
whenNew("com.example.OuterClass$InnerClass")
.withNoArguments()
.thenReturn(mockInnerInstance);Base interface providing argument specification options.
interface WithOrWithoutExpectedArguments<T> extends WithExpectedArguments<T>, WithoutExpectedArguments<T> {}Interface for specifying expected method arguments.
interface WithExpectedArguments<T> {
OngoingStubbing<T> withArguments(Object firstArgument, Object... additionalArguments) throws Exception;
}Usage Example:
when(service, privateMethod)
.withArguments("param1", 42, true)
.thenReturn("result");Interface for methods called without arguments.
interface WithoutExpectedArguments<T> {
OngoingStubbing<T> withNoArguments() throws Exception;
}Usage Example:
// Expect no arguments
when(service, privateMethod)
.withNoArguments()
.thenReturn("no_args_result");Interface for methods called with any arguments.
interface WithAnyArguments<T> {
OngoingStubbing<T> withAnyArguments() throws Exception;
}Usage Example:
// Accept any arguments
when(service, privateMethod)
.withAnyArguments()
.thenReturn("any_args_result");Comprehensive interface for constructor expectation configuration.
interface ConstructorExpectationSetup<T> extends WithOrWithoutExpectedArguments<T>,
WithExpectedParameterTypes<T>, WithAnyArguments<T> {}Interface for specifying expected parameters by type.
interface WithExpectedParameterTypes<T> {
WithExpectedArguments<T> withParameterTypes(Class<?> parameterType, Class<?>... additionalParameterTypes);
}Usage Example:
whenNew(Service.class)
.withParameterTypes(String.class, Integer.class)
.withArguments("test", 42)
.thenReturn(mockService);Interface for accepting any argument combination.
interface WithAnyArguments<T> {
OngoingStubbing<T> withAnyArguments() throws Exception;
}UserService service = spy(new UserService());
// Chain multiple private method expectations
when(service, "validateUser", any(User.class))
.thenReturn(true);
when(service, "logAccess", anyString(), any(Date.class))
.thenReturn(null);
// Constructor expectations with different argument patterns
whenNew(AuditLog.class)
.withNoArguments()
.thenReturn(mockAuditLog);
whenNew(AuditLog.class)
.withArguments(anyString())
.thenReturn(mockAuditLog);// Private method throwing exceptions
when(validator, "checkBusinessRules", invalidData)
.thenThrow(new ValidationException("Invalid data"));
// Constructor throwing exceptions
whenNew(DatabaseConnection.class)
.withArguments("invalid_url")
.thenThrow(new SQLException("Connection failed"));import static org.mockito.ArgumentMatchers.*;
// Use argument matchers for flexible expectations
when(service, "processData", any(DataModel.class), eq(true))
.thenReturn("processed");
when(calculator, "compute", gt(100), anyDouble())
.thenReturn(42.0);
// Constructor with argument matchers
whenNew(FileReader.class)
.withArguments(startsWith("/tmp/"), eq("UTF-8"))
.thenReturn(mockReader);// Different responses based on arguments
when(service, "authenticate", "admin", anyString())
.thenReturn(true);
when(service, "authenticate", "guest", anyString())
.thenReturn(false);
// Multiple return values
when(generator, "nextValue")
.thenReturn(1, 2, 3, 4, 5);try {
when(service, "nonExistentMethod").thenReturn("value");
} catch (Exception e) {
// Handle cases where private method doesn't exist
fail("Private method setup failed: " + e.getMessage());
}Install with Tessl CLI
npx tessl i tessl/maven-org-powermock--powermock-api-mockito2