CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-powermock--powermock-api-mockito2

PowerMock API for Mockito 2.+ that enables advanced mocking of static methods, constructors, final classes and private methods through bytecode manipulation.

Pending
Overview
Eval results
Files

stubbing.mddocs/

Stubbing

PowerMock's stubbing system extends Mockito's capabilities with the PowerMockitoStubber interface, enabling advanced stubbing scenarios for void methods, private methods, static methods, and complex stubbing patterns that standard Mockito cannot handle.

Basic Stubbing Methods

Answer-Based Stubbing

Stub methods to execute custom Answer implementations.

public static PowerMockitoStubber doAnswer(Answer<?> answer);

Configure methods to execute custom logic when called, useful for complex return value computation or side effects.

Parameters:

  • answer - Custom Answer implementation defining the stubbing behavior

Returns:

  • PowerMockitoStubber - Extended stubber for PowerMock-specific stubbing scenarios

Usage Example:

UserService service = spy(new UserService());

doAnswer(invocation -> {
    String username = invocation.getArgument(0);
    if ("admin".equals(username)) {
        return "Administrator User";
    }
    return "Regular User";
}).when(service, "getDisplayName", anyString());

String adminName = service.getDisplayName("admin");
String userNmae = service.getDisplayName("john");

assertEquals("Administrator User", adminName);
assertEquals("Regular User", userNmae);

Exception Stubbing

Stub methods to throw specific exceptions.

public static PowerMockitoStubber doThrow(Throwable toBeThrown);

Configure methods to throw exceptions when called, essential for testing error handling scenarios.

Usage Example:

DatabaseService dbService = spy(new DatabaseService());

doThrow(new SQLException("Connection timeout"))
    .when(dbService, "executeQuery", anyString());

// Test error handling
try {
    dbService.executeQuery("SELECT * FROM users");
    fail("Expected SQLException");
} catch (SQLException e) {
    assertEquals("Connection timeout", e.getMessage());
}

Real Method Calling

Stub methods to call their real implementations.

public static PowerMockitoStubber doCallRealMethod();

Configure mocked methods to execute their actual implementation, useful for partial mocking scenarios.

Usage Example:

Calculator calculator = mock(Calculator.class);

// Most methods are mocked, but allow real implementation for basic operations
doCallRealMethod().when(calculator).add(anyInt(), anyInt());

// Mock complex operations
when(calculator.complexCalculation(anyDouble())).thenReturn(42.0);

int result = calculator.add(5, 3); // calls real method, returns 8
double complex = calculator.complexCalculation(100); // returns mocked value 42.0

Do Nothing Stubbing

Stub void methods to do nothing.

public static PowerMockitoStubber doNothing();

Explicitly configure void methods to do nothing, useful for consecutive stubbing or spy scenarios.

Usage Example:

Logger logger = spy(new Logger());

// First call does nothing, second call throws exception
doNothing()
    .doThrow(new RuntimeException("Logging failed"))
    .when(logger).log(anyString());

logger.log("First message"); // does nothing
try {
    logger.log("Second message"); // throws exception
} catch (RuntimeException e) {
    assertEquals("Logging failed", e.getMessage());
}

Return Value Stubbing

Stub methods to return specific values.

public static PowerMockitoStubber doReturn(Object toBeReturned);
public static PowerMockitoStubber doReturn(Object toBeReturned, Object... othersToBeReturned);

Configure methods to return specific values, essential when when().thenReturn() cannot be used (e.g., with spies that would execute real methods).

Parameters:

  • toBeReturned - First value to return
  • othersToBeReturned - Additional values for consecutive calls

Usage Examples:

FileService fileService = spy(new FileService());

// Single return value
doReturn("file content")
    .when(fileService, "readPrivateFile", "/secret/config.txt");

// Multiple consecutive return values
doReturn("first", "second", "third")
    .when(fileService, "getNextLine");

String content = fileService.readPrivateFile("/secret/config.txt"); // "file content"
String line1 = fileService.getNextLine(); // "first"
String line2 = fileService.getNextLine(); // "second" 
String line3 = fileService.getNextLine(); // "third"

PowerMockitoStubber Interface

The PowerMockitoStubber extends Mockito's Stubber with PowerMock-specific capabilities:

interface PowerMockitoStubber extends Stubber {
    void when(Class<?> classMock);
    <T> PrivatelyExpectedArguments when(T mock, Method method) throws Exception;
    <T> void when(T mock, Object... arguments) throws Exception;
    <T> void when(T mock, String methodToExpect, Object... arguments) throws Exception;
    <T> PrivatelyExpectedArguments when(Class<T> classMock, Method method) throws Exception;
    <T> void when(Class<T> classMock, Object... arguments) throws Exception;
    <T> void when(Class<T> classMock, String methodToExpect, Object... arguments) throws Exception;
}

Stubbing Static Methods

Basic Static Method Stubbing

void when(Class<?> classMock);

Select a static method for stubbing using the standard method call syntax.

Usage Example:

mockStatic(FileUtils.class);

doReturn("mocked content")
    .when(FileUtils.class);
FileUtils.readFile("config.txt");

String content = FileUtils.readFile("config.txt");
assertEquals("mocked content", content);

Stubbing Private Instance Methods

Private Method Stubbing with Method Objects

<T> PrivatelyExpectedArguments when(T mock, Method method) throws Exception;

Stub private instance methods using Method objects for precise identification.

Usage Example:

UserService service = spy(new UserService());
Method privateMethod = PowerMockito.method(UserService.class, "encryptPassword", String.class);

doReturn("encrypted_password")
    .when(service, privateMethod)
    .withArguments("plaintext");

Private Method Stubbing by Arguments

<T> void when(T mock, Object... arguments) throws Exception;

Stub private methods by providing arguments that PowerMock uses to identify the target method.

Usage Example:

Calculator calc = spy(new Calculator());

doReturn(100.0)
    .when(calc, 10.0, 5.0); // PowerMock finds private method(double, double)

doThrow(new IllegalArgumentException())
    .when(calc, "invalid"); // PowerMock finds private method(String)

Private Method Stubbing by Name

<T> void when(T mock, String methodToExpected, Object... arguments) throws Exception;

Stub private methods by explicitly specifying the method name and arguments.

Usage Example:

DataProcessor processor = spy(new DataProcessor());

doAnswer(invocation -> {
    String data = invocation.getArgument(0);
    return data.toUpperCase();
}).when(processor, "transformData", anyString());

// Execute code that calls private transformData method
String result = processor.processInput("hello world");
assertEquals("HELLO WORLD", result);

Stubbing Static Private Methods

Static Private Method with Method Objects

<T> PrivatelyExpectedArguments when(Class<T> classMock, Method method) throws Exception;

Usage Example:

Method staticPrivateMethod = PowerMockito.method(CryptoUtils.class, "generateSalt", int.class);

doReturn("generated_salt")
    .when(CryptoUtils.class, staticPrivateMethod)
    .withArguments(32);

Static Private Method by Arguments

<T> void when(Class<T> classMock, Object... arguments) throws Exception;

Usage Example:

doReturn("computed_hash")
    .when(HashUtils.class, "secretData", 256);

Static Private Method by Name

<T> void when(Class<T> classMock, String methodToExpected, Object... arguments) throws Exception;

Usage Example:

doThrow(new SecurityException("Access denied"))
    .when(SecurityUtils.class, "checkInternalPermission", "admin");

PrivatelyExpectedArguments Interface

Interface for specifying arguments when stubbing private methods with Method objects:

interface PrivatelyExpectedArguments {
    <T> void withArguments(Object firstArgument, Object... additionalArguments) throws Exception;
    <T> void withNoArguments() throws Exception;
}

Usage Examples:

Method privateMethod = PowerMockito.method(Service.class, "helper", String.class, int.class);

// Specific arguments
doReturn("result")
    .when(service, privateMethod)
    .withArguments("test", 42);

// No arguments
doNothing()
    .when(service, privateMethod)
    .withNoArguments();

Advanced Stubbing Patterns

Consecutive Stubbing

UserService service = spy(new UserService());

// Different behaviors for consecutive calls
doReturn(true)
    .doReturn(false)
    .doThrow(new RuntimeException("Max attempts exceeded"))
    .when(service, "authenticate", anyString(), anyString());

boolean result1 = service.authenticate("user", "pass"); // true
boolean result2 = service.authenticate("user", "pass"); // false
// Third call throws exception

Conditional Stubbing

DatabaseService dbService = spy(new DatabaseService());

doAnswer(invocation -> {
    String query = invocation.getArgument(0);
    if (query.contains("DROP")) {
        throw new SecurityException("DROP operations not allowed");
    }
    return "Query executed successfully";
}).when(dbService, "executeQuery", anyString());

Argument Matchers in Stubbing

import static org.mockito.ArgumentMatchers.*;

// Use argument matchers for flexible stubbing
doReturn("admin_result")
    .when(service, "processRequest", eq("admin"), any());

doThrow(new IllegalArgumentException())
    .when(validator, "validate", argThat(data -> data.length() < 5));

Error Handling in Stubbing

try {
    doReturn("value")
        .when(service, "nonExistentMethod", "param");
} catch (Exception e) {
    // Handle cases where method doesn't exist or isn't accessible
    logger.warn("Stubbing setup failed: " + e.getMessage());
}

Combining Stubbing with Verification

EmailService emailService = spy(new EmailService());

// Stub private method
doNothing()
    .when(emailService, "logEmail", anyString());

// Execute code under test
emailService.sendNotification("user@example.com", "message");

// Verify private method was called
verifyPrivate(emailService).invoke("logEmail", contains("user@example.com"));

Member Introspection for Stubbing

PowerMock provides powerful member introspection utilities for finding methods by name, parameter types, or class hierarchy traversal. These are essential for precise private method stubbing.

Method Finding by Name and Parameters

public static Method method(Class<?> declaringClass, String methodName, Class<?>... parameterTypes);

Find a specific method by name and exact parameter types.

Usage Example:

// Find specific private method for stubbing
Method privateMethod = PowerMockito.method(UserService.class, "encryptPassword", String.class);

doReturn("encrypted_password")
    .when(userService, privateMethod)
    .withArguments("plaintext");

Method Finding by Parameters Only

public static Method method(Class<?> declaringClass, Class<?>... parameterTypes);

Find a method by parameter types alone (useful when method name is unique by parameters).

Usage Example:

// Find method by parameter signature
Method uniqueMethod = PowerMockito.method(CryptoService.class, String.class, byte[].class);

doThrow(new CryptoException())
    .when(cryptoService, uniqueMethod)
    .withArguments(anyString(), any(byte[].class));

Multiple Method Finding

public static Method[] methods(Class<?> clazz, String methodName, String... additionalMethodNames);

Get multiple methods by names for batch stubbing operations.

Usage Example:

// Find multiple methods for comprehensive stubbing
Method[] authMethods = PowerMockito.methods(AuthService.class, "authenticate", "authorize", "validate");

for (Method method : authMethods) {
    doReturn(true)
        .when(authService, method)
        .withArguments(any());
}

Class Hierarchy Method Discovery

public static Method[] methodsDeclaredIn(Class<?> cls, Class<?>... additionalClasses);

Get all methods from a class hierarchy for comprehensive stubbing.

Usage Example:

// Get all methods from service and its parent classes
Method[] allMethods = PowerMockito.methodsDeclaredIn(UserService.class, BaseService.class);

// Stub all void methods to do nothing
for (Method method : allMethods) {
    if (method.getReturnType() == void.class) {
        doNothing().when(userService, method);
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-org-powermock--powermock-api-mockito2

docs

expectations.md

index.md

mock-creation.md

stubbing.md

verification.md

tile.json