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

verification.mddocs/

Verification

PowerMock's verification system provides comprehensive capabilities for verifying static method calls, private method invocations, constructor calls, and general mock interactions. This extends standard Mockito verification to cover traditionally difficult-to-test scenarios.

Static Method Verification

Basic Static Verification

Verify that static methods were called exactly once.

public static <T> void verifyStatic(Class<T> mockedClass);

Verifies that static methods on the specified class were called once. This is equivalent to verifyStatic(mockedClass, times(1)).

Parameters:

  • mockedClass - The class whose static methods should be verified

Usage Example:

// Setup static mock
mockStatic(FileUtils.class);
when(FileUtils.readFile("config.txt")).thenReturn("config data");

// Execute code under test
String config = MyService.loadConfiguration(); // internally calls FileUtils.readFile

// Verify static method was called
verifyStatic(FileUtils.class);
FileUtils.readFile("config.txt");

Static Verification with Mode

Verify static method calls with specific verification modes.

public static <T> void verifyStatic(Class<T> mockedClass, VerificationMode verificationMode);

Verifies static method calls with custom verification modes like times(), atLeast(), never(), etc.

Parameters:

  • mockedClass - The class whose static methods should be verified
  • verificationMode - Verification mode (e.g., times(2), atLeastOnce(), never())

Usage Example:

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.never;

// Verify called exactly 3 times
verifyStatic(LoggerUtils.class, times(3));
LoggerUtils.log(anyString());

// Verify called at least twice
verifyStatic(CacheUtils.class, atLeast(2));
CacheUtils.clear();

// Verify never called
verifyStatic(SecurityUtils.class, never());
SecurityUtils.authenticate(anyString());

Private Method Verification

Basic Private Method Verification

Verify private method calls on object instances.

public static PrivateMethodVerification verifyPrivate(Object object);

Returns a verification object for verifying private method calls on the specified instance. Defaults to verifying calls happened once.

Parameters:

  • object - The object whose private methods should be verified

Returns:

  • PrivateMethodVerification - Verification interface for specifying method details

Usage Example:

UserService userService = spy(new UserService());

// Execute code that should call private method
userService.processUser(testUser);

// Verify private method was called
verifyPrivate(userService).invoke("validateUser", testUser);

Private Method Verification with Mode

Verify private method calls with specific verification modes.

public static PrivateMethodVerification verifyPrivate(Object object, VerificationMode verificationMode);

Usage Example:

verifyPrivate(processor, times(2)).invoke("processData", any());
verifyPrivate(calculator, never()).invoke("recalculate");

Static Private Method Verification

Verify private static method calls on classes.

public static PrivateMethodVerification verifyPrivate(Class<?> clazz) throws Exception;
public static PrivateMethodVerification verifyPrivate(Class<?> clazz, VerificationMode verificationMode);

Usage Example:

// Verify static private method called once
verifyPrivate(UtilityClass.class).invoke("internalHelper", "param");

// Verify static private method called multiple times
verifyPrivate(ConfigParser.class, times(3)).invoke("parseSection", anyString());

Private Method Verification Interface

The PrivateMethodVerification interface provides methods for specifying which private method to verify:

interface PrivateMethodVerification {
    void invoke(String methodToVerify, Object... arguments) throws Exception;
    WithOrWithoutVerifiedArguments invoke(Method method) throws Exception;
    @Deprecated
    void invoke(Object... arguments) throws Exception;
}

Verify by Method Name

// Verify private method by name with specific arguments
verifyPrivate(service).invoke("processOrder", orderId, userId);

// Verify with argument matchers
verifyPrivate(validator).invoke("checkEmail", anyString());

Verify by Method Object

Method privateMethod = PowerMockito.method(MyClass.class, "privateHelper", String.class);
verifyPrivate(instance).invoke(privateMethod);

Constructor Verification

Basic Constructor Verification

Verify that constructors were called during test execution.

public static <T> ConstructorArgumentsVerification verifyNew(Class<T> mock);

Verifies that the constructor of the specified class was called once.

Usage Example:

// Setup constructor mocking
MyService mockService = mock(MyService.class);
whenNew(MyService.class).withAnyArguments().thenReturn(mockService);

// Execute code that creates instances
MyController controller = new MyController(); // internally creates MyService

// Verify constructor was called
verifyNew(MyService.class);

Constructor Verification with Mode

public static <T> ConstructorArgumentsVerification verifyNew(Class<T> mock, VerificationMode mode);

Usage Example:

verifyNew(DatabaseConnection.class, times(2));
verifyNew(FileProcessor.class, never());

Constructor Arguments Verification Interface

The ConstructorArgumentsVerification interface allows verification of specific constructor arguments:

interface ConstructorArgumentsVerification {
    void withArguments(Object argument, Object... additionalArguments) throws Exception;
    void withNoArguments() throws Exception;
}

Usage Examples:

// Verify constructor called with specific arguments
verifyNew(UserService.class).withArguments("admin", "password");

// Verify no-arg constructor
verifyNew(DefaultLogger.class).withNoArguments();

General Verification

Verify No More Interactions

Ensure no unverified interactions occurred on mocks.

public static void verifyNoMoreInteractions(Object... mocks);

Checks that all interactions with the specified mocks have been verified. Useful for ensuring complete test coverage.

Usage Example:

UserService userMock = mock(UserService.class);
OrderService orderMock = mock(OrderService.class);

// Setup and execute test...
when(userMock.getUser(1L)).thenReturn(testUser);
userMock.getUser(1L);

// Verify expected interactions
verify(userMock).getUser(1L);

// Ensure no other interactions occurred
verifyNoMoreInteractions(userMock, orderMock);

Verify Zero Interactions

Verify that no interactions occurred on the specified mocks.

public static void verifyZeroInteractions(Object... mocks);

Usage Example:

EmailService emailMock = mock(EmailService.class);
SmsService smsMock = mock(SmsService.class);

// Execute test that shouldn't trigger notifications
userService.updateProfile(user);

// Verify no notification services were called
verifyZeroInteractions(emailMock, smsMock);

Advanced Verification Patterns

Combining Verification Types

// Verify static methods
verifyStatic(SecurityUtils.class);
SecurityUtils.checkPermission("admin");

// Verify private methods
verifyPrivate(service).invoke("auditAction", "update");

// Verify constructors
verifyNew(AuditLog.class).withArguments("update", userId);

// Ensure no other interactions
verifyNoMoreInteractions(mockDependency);

Verification with Argument Matchers

import static org.mockito.ArgumentMatchers.*;

// Static method verification with matchers
verifyStatic(LoggerUtils.class, times(2));
LoggerUtils.log(eq("INFO"), contains("user"));

// Private method verification with matchers
verifyPrivate(processor).invoke("processItem", any(Item.class), eq(true));

// Constructor verification with matchers
verifyNew(Connection.class).withArguments(startsWith("jdbc:"), anyString());

Error Handling in Verification

try {
    verifyPrivate(service).invoke("nonExistentMethod");
} catch (Exception e) {
    // Handle reflection errors when method doesn't exist
    fail("Private method not found: " + 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