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

expectations.mddocs/

Expectation Setup

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.

Method Expectation Setup

Private Method Expectations by Name

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 method
  • methodName - Name of the private method to expect
  • arguments - Expected arguments for the method call

Returns:

  • OngoingStubbing<T> - Standard Mockito stubbing interface for configuring return values

Usage 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);

Method Object-Based Expectations

Set up expectations using Method objects for precise method identification.

public static <T> WithOrWithoutExpectedArguments<T> when(Object instance, Method method);

Parameters:

  • instance - The object instance
  • method - Method object obtained via reflection

Returns:

  • WithOrWithoutExpectedArguments<T> - Fluent interface for argument specification

Usage Example:

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

when(service, privateMethod)
    .withArguments("sensitive")
    .thenReturn("encrypted_sensitive");

Static Method Expectations

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");

Dynamic Method Resolution

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)

Static Method Expectations by Name

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);

Constructor Expectation Setup

Constructor-Based Expectations

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 for

Usage 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 mockConnection

Class-Based Constructor Expectations

Configure constructor expectations using class types.

public static <T> ConstructorExpectationSetup<T> whenNew(Class<T> type);

Parameters:

  • type - Class whose constructor should be mocked

Returns:

  • ConstructorExpectationSetup<T> - Fluent interface for constructor argument specification

Usage Example:

FileProcessor mockProcessor = mock(FileProcessor.class);

whenNew(FileProcessor.class)
    .withArguments("/tmp/data.txt")
    .thenReturn(mockProcessor);

// Any new FileProcessor("/tmp/data.txt") will return mockProcessor

Inner Class Constructor Expectations

Handle 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 class

Usage Example:

// Mock inner class constructor
whenNew("com.example.OuterClass$InnerClass")
    .withNoArguments()
    .thenReturn(mockInnerInstance);

Expectation Setup Interfaces

WithOrWithoutExpectedArguments Interface

Base interface providing argument specification options.

interface WithOrWithoutExpectedArguments<T> extends WithExpectedArguments<T>, WithoutExpectedArguments<T> {}

WithExpectedArguments Interface

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");

WithoutExpectedArguments Interface

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");

WithAnyArguments Interface

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");

ConstructorExpectationSetup Interface

Comprehensive interface for constructor expectation configuration.

interface ConstructorExpectationSetup<T> extends WithOrWithoutExpectedArguments<T>, 
    WithExpectedParameterTypes<T>, WithAnyArguments<T> {}

WithExpectedParameterTypes Interface

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);

WithAnyArguments Interface

Interface for accepting any argument combination.

interface WithAnyArguments<T> {
    OngoingStubbing<T> withAnyArguments() throws Exception;
}

Advanced Expectation Patterns

Chaining Multiple Expectations

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);

Exception Expectations

// 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"));

Argument Matchers in Expectations

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);

Conditional Expectations

// 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);

Error Handling in Expectations

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

docs

expectations.md

index.md

mock-creation.md

stubbing.md

verification.md

tile.json