CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-powermock--powermock-api-mockito

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

Pending
Overview
Eval results
Files

verification-extensions.mddocs/

Verification Extensions

PowerMock extends Mockito's verification capabilities to work seamlessly with static methods, final classes, and other enhanced mocking features. These extensions ensure comprehensive verification coverage for all types of mocked interactions.

Capabilities

No More Interactions Verification

Verify that no additional interactions occurred on PowerMock-enhanced mocks beyond what has already been verified.

static void verifyNoMoreInteractions(Object... mocks);

Parameters:

  • mocks - Variable number of mock objects (both instance and class mocks) to verify

Usage Example:

@Test
@PrepareForTest({DatabaseService.class, Logger.class})
public void testNoMoreInteractions() {
    mockStatic(Logger.class);
    DatabaseService dbMock = mock(DatabaseService.class);
    when(dbMock.findUser("123")).thenReturn(mockUser);
    
    UserService service = new UserService(dbMock);
    User result = service.getUser("123");
    
    // Verify expected interactions
    verify(dbMock).findUser("123");
    verifyStatic(Logger.class);
    Logger.log("User retrieved: 123");
    
    // Verify no additional interactions occurred
    verifyNoMoreInteractions(dbMock);
    verifyNoMoreInteractions(Logger.class);
}

Zero Interactions Verification

Verify that no interactions occurred at all on the specified mocks.

static void verifyZeroInteractions(Object... mocks);

Parameters:

  • mocks - Variable number of mock objects to verify for zero interactions

Usage Example:

@Test
@PrepareForTest({ExternalService.class, AuditLogger.class})
public void testZeroInteractions() {
    mockStatic(ExternalService.class);
    mockStatic(AuditLogger.class);
    
    LocalService service = new LocalService();
    service.performLocalOperation(); // Should not call external services
    
    // Verify no external calls were made
    verifyZeroInteractions(ExternalService.class);
    verifyZeroInteractions(AuditLogger.class);
}

Common Patterns

Comprehensive Interaction Verification

@Test
@PrepareForTest({SecurityService.class, NotificationService.class})
public void testComprehensiveVerification() {
    mockStatic(SecurityService.class);
    mockStatic(NotificationService.class);
    EmailService emailMock = mock(EmailService.class);
    
    when(SecurityService.isAuthorized("user123")).thenReturn(true);
    when(emailMock.sendEmail(anyString(), anyString())).thenReturn(true);
    
    UserManager manager = new UserManager(emailMock);
    manager.processUserAction("user123", "update_profile");
    
    // Verify all expected interactions
    verifyStatic(SecurityService.class);
    SecurityService.isAuthorized("user123");
    
    verify(emailMock).sendEmail("user123", "Profile updated");
    
    verifyStatic(NotificationService.class);
    NotificationService.sendNotification("user123", "SUCCESS");
    
    // Ensure no unexpected interactions occurred
    verifyNoMoreInteractions(SecurityService.class, NotificationService.class, emailMock);
}

Conditional Verification with Zero Interactions

@Test
@PrepareForTest(AlertService.class)
public void testConditionalVerification() {
    mockStatic(AlertService.class);
    
    SystemMonitor monitor = new SystemMonitor();
    
    // Test normal operation - no alerts should be sent
    monitor.checkSystemHealth(95); // 95% healthy
    verifyZeroInteractions(AlertService.class);
    
    // Test critical condition - alert should be sent
    monitor.checkSystemHealth(15); // 15% healthy
    verifyStatic(AlertService.class);
    AlertService.sendCriticalAlert(contains("System health critical"));
    
    // Reset and verify no more interactions
    reset(AlertService.class);
    monitor.checkSystemHealth(85); // Back to normal
    verifyZeroInteractions(AlertService.class);
}

Mixed Mock Types Verification

@Test
@PrepareForTest({FileUtils.class, DatabaseLogger.class})
public void testMixedMockVerification() {
    mockStatic(FileUtils.class);
    mockStatic(DatabaseLogger.class);
    CacheService cacheMock = mock(CacheService.class);
    
    when(FileUtils.readFile("config.properties")).thenReturn("app.name=TestApp");
    when(cacheMock.get("config")).thenReturn(null);
    
    ConfigurationManager manager = new ConfigurationManager(cacheMock);
    manager.loadConfiguration();
    
    // Verify interactions with all mock types
    verifyStatic(FileUtils.class);
    FileUtils.readFile("config.properties");
    
    verify(cacheMock).get("config");
    verify(cacheMock).put(eq("config"), any(Properties.class));
    
    verifyStatic(DatabaseLogger.class);
    DatabaseLogger.logConfigurationLoad();
    
    // Comprehensive verification - no more interactions on any mock
    verifyNoMoreInteractions(FileUtils.class, DatabaseLogger.class, cacheMock);
}

Error Scenario Verification

@Test
@PrepareForTest({ErrorReporter.class, RecoveryService.class})
public void testErrorScenarioVerification() {
    mockStatic(ErrorReporter.class);
    mockStatic(RecoveryService.class);
    
    doThrow(new RuntimeException("System failure")).when(ErrorReporter.class);
    ErrorReporter.reportError(anyString());
    
    SystemService service = new SystemService();
    
    assertThrows(SystemException.class, () -> {
        service.performCriticalOperation();
    });
    
    // Verify error reporting was attempted
    verifyStatic(ErrorReporter.class);
    ErrorReporter.reportError(contains("Critical operation failed"));
    
    // Verify recovery service was never called due to error reporter failure
    verifyZeroInteractions(RecoveryService.class);
    
    // Verify no unexpected interactions
    verifyNoMoreInteractions(ErrorReporter.class);
}

Stubbed vs Unstubbed Verification

@Test
@PrepareForTest(MetricsCollector.class) 
public void testStubbedVsUnstubbedVerification() {
    mockStatic(MetricsCollector.class);
    
    // Stub only specific method call
    when(MetricsCollector.recordMetric("user.login", 1)).thenReturn(true);
    
    AuthenticationService service = new AuthenticationService();
    service.authenticateUser("user123");
    
    // Verify stubbed interaction occurred
    verifyStatic(MetricsCollector.class);
    MetricsCollector.recordMetric("user.login", 1);
    
    // This would fail if unstubbed methods were also called
    verifyNoMoreInteractions(MetricsCollector.class);
}

Verification with Timing Constraints

@Test
@PrepareForTest({AsyncProcessor.class, NotificationQueue.class})
public void testAsyncVerification() throws Exception {
    mockStatic(AsyncProcessor.class);
    mockStatic(NotificationQueue.class);
    
    EventHandler handler = new EventHandler();
    handler.handleEvent("user_registered", userData);
    
    // Verify async processing was triggered
    verifyStatic(AsyncProcessor.class, timeout(2000));
    AsyncProcessor.processAsync(eq("user_registered"), any());
    
    // Wait and verify notification was queued
    verifyStatic(NotificationQueue.class, timeout(3000));
    NotificationQueue.enqueue(any(Notification.class));
    
    // Verify no other interactions occurred during the timeout period
    Thread.sleep(1000);
    verifyNoMoreInteractions(AsyncProcessor.class, NotificationQueue.class);
}

Verification Order with Multiple Mock Types

@Test
@PrepareForTest({ValidationService.class, AuditService.class})
public void testVerificationOrder() {
    mockStatic(ValidationService.class);
    mockStatic(AuditService.class);
    DatabaseMock dbMock = mock(DatabaseMock.class);
    
    when(ValidationService.validate(any())).thenReturn(true);
    when(dbMock.save(any())).thenReturn(true);
    
    InOrder inOrder = inOrder(ValidationService.class, dbMock, AuditService.class);
    
    DataService service = new DataService(dbMock);
    service.saveData(testData);
    
    // Verify correct order of operations
    verifyStatic(ValidationService.class, inOrder);
    ValidationService.validate(testData);
    
    verify(dbMock, inOrder).save(testData);
    
    verifyStatic(AuditService.class, inOrder);
    AuditService.logDataSave(testData.getId());
    
    // Verify no additional interactions after ordered sequence
    verifyNoMoreInteractions(ValidationService.class, AuditService.class, dbMock);
}

Integration with Standard Mockito Verification

PowerMock's verification extensions work seamlessly with standard Mockito verification:

@Test
@PrepareForTest(StaticHelper.class)
public void testIntegratedVerification() {
    mockStatic(StaticHelper.class);
    ServiceDependency mockDep = mock(ServiceDependency.class);
    
    when(StaticHelper.getValue()).thenReturn("static-value");
    when(mockDep.process(anyString())).thenReturn("processed");
    
    BusinessService service = new BusinessService(mockDep);
    service.execute();
    
    // Standard Mockito verification
    verify(mockDep).process("static-value");
    verify(mockDep, times(1)).process(anyString());
    
    // PowerMock static verification  
    verifyStatic(StaticHelper.class);
    StaticHelper.getValue();
    
    // Combined verification extensions
    verifyNoMoreInteractions(mockDep, StaticHelper.class);
}

Benefits

Comprehensive Test Coverage

  • Ensures all mock interactions are accounted for
  • Prevents over-mocking and unnecessary stub setup
  • Validates that tests are focused and minimal

Regression Detection

  • Catches unexpected method calls introduced by code changes
  • Identifies when refactoring changes interaction patterns
  • Ensures test assumptions remain valid over time

Test Maintenance

  • Makes tests more strict and precise
  • Reduces false positives from over-stubbing
  • Improves test reliability and trustworthiness

Requirements

  • Works with all PowerMock-enhanced mocks (static, final, private methods)
  • Compatible with standard Mockito verification modes and patterns
  • Must be called after all expected verifications are complete
  • Can be used with both class mocks and instance mocks simultaneously

Install with Tessl CLI

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

docs

advanced-stubbing.md

constructor-mocking.md

index.md

object-mocking.md

private-methods.md

static-mocking.md

static-verification.md

verification-extensions.md

tile.json