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
—
PowerMock provides comprehensive verification capabilities for static method calls, enabling you to verify that static methods were called with expected arguments and frequencies. This complements static mocking by providing the same verification guarantees for static methods as Mockito provides for instance methods.
Verify that static methods on a specific class were called exactly once.
static <T> void verifyStatic(Class<T> mockedClass);Parameters:
mockedClass - The class whose static method calls should be verifiedUsage Example:
@Test
@PrepareForTest(Logger.class)
public void testBasicStaticVerification() {
mockStatic(Logger.class);
// Code under test that calls static method
MyService service = new MyService();
service.performOperation();
// Verify static method was called once
verifyStatic(Logger.class);
Logger.log("Operation completed");
}Verify that static methods were called with specific verification modes (times, atLeast, never, etc.).
static <T> void verifyStatic(Class<T> mockedClass, VerificationMode verificationMode);Parameters:
mockedClass - The class whose static method calls should be verifiedverificationMode - The verification mode (times(n), atLeast(n), atMost(n), never(), etc.)Usage Example:
@Test
@PrepareForTest(SecurityAudit.class)
public void testStaticVerificationWithMode() {
mockStatic(SecurityAudit.class);
UserService service = new UserService();
service.loginUser("user1");
service.loginUser("user2");
service.loginUser("user3");
// Verify audit log was called exactly 3 times
verifyStatic(SecurityAudit.class, times(3));
SecurityAudit.logLogin(anyString());
// Verify security check was called at least once
verifyStatic(SecurityAudit.class, atLeast(1));
SecurityAudit.performSecurityCheck();
}PowerMock supports all standard Mockito verification modes:
times(n) // Exactly n times
atLeast(n) // At least n times
atMost(n) // At most n times
never() // Never called
atLeastOnce() // At least once (same as atLeast(1))
only() // Only this method was called on the mock@Test
@PrepareForTest(StringUtils.class)
public void testUtilityVerification() {
mockStatic(StringUtils.class);
when(StringUtils.isEmpty(anyString())).thenReturn(false);
DataValidator validator = new DataValidator();
validator.validateInput("test input");
// Verify utility method was used for validation
verifyStatic(StringUtils.class);
StringUtils.isEmpty("test input");
// Verify trimming was also performed
verifyStatic(StringUtils.class);
StringUtils.trim("test input");
}@Test
@PrepareForTest(DatabaseLogger.class)
public void testComplexArgumentVerification() {
mockStatic(DatabaseLogger.class);
OrderProcessor processor = new OrderProcessor();
Order order = new Order("12345", new BigDecimal("99.99"));
processor.processOrder(order);
// Verify static method was called with specific object
verifyStatic(DatabaseLogger.class);
DatabaseLogger.logTransaction(eq(order.getId()), eq(order.getAmount()));
// Verify using matchers for complex objects
verifyStatic(DatabaseLogger.class);
DatabaseLogger.logTransaction(matches("\\d{5}"), any(BigDecimal.class));
}@Test
@PrepareForTest({ConfigManager.class, CacheManager.class})
public void testMultipleStaticVerifications() {
mockStatic(ConfigManager.class);
mockStatic(CacheManager.class);
when(ConfigManager.getProperty("cache.enabled")).thenReturn("true");
ApplicationService service = new ApplicationService();
service.initialize();
// Verify configuration was checked
verifyStatic(ConfigManager.class);
ConfigManager.getProperty("cache.enabled");
// Verify cache was initialized based on config
verifyStatic(CacheManager.class);
CacheManager.initialize();
// Verify cache was not disabled
verifyStatic(CacheManager.class, never());
CacheManager.disable();
}@Test
@PrepareForTest(SystemLogger.class)
public void testStaticCallOrder() {
mockStatic(SystemLogger.class);
InOrder inOrder = inOrder(SystemLogger.class);
StartupService service = new StartupService();
service.startup();
// Verify static methods were called in specific order
verifyStatic(SystemLogger.class, inOrder);
SystemLogger.log("Starting application");
verifyStatic(SystemLogger.class, inOrder);
SystemLogger.log("Loading configuration");
verifyStatic(SystemLogger.class, inOrder);
SystemLogger.log("Application started");
}@Test
@PrepareForTest(ExternalService.class)
public void testNoStaticInteractions() {
mockStatic(ExternalService.class);
LocalService service = new LocalService();
service.performLocalOperation();
// Verify external service was never called for local operations
verifyStatic(ExternalService.class, never());
ExternalService.callExternalAPI(anyString());
// Alternative: verify no interactions at all
verifyNoMoreInteractions(ExternalService.class);
}@Test
@PrepareForTest(NotificationService.class)
public void testConditionalStaticVerification() {
mockStatic(NotificationService.class);
EmailService emailService = new EmailService();
// Test with notifications enabled
emailService.sendEmail("user@example.com", "subject", "body", true);
verifyStatic(NotificationService.class);
NotificationService.sendNotification(anyString());
// Reset static mock
reset(NotificationService.class);
// Test with notifications disabled
emailService.sendEmail("user@example.com", "subject", "body", false);
verifyStatic(NotificationService.class, never());
NotificationService.sendNotification(anyString());
}@Test
@PrepareForTest(MetricsCollector.class)
public void testArgumentMatchers() {
mockStatic(ReflectionHelper.class);
ReportGenerator generator = new ReportGenerator();
generator.generateReport("sales", LocalDate.now());
// Verify with argument matchers
verifyStatic(MetricsCollector.class);
MetricsCollector.recordMetric(
eq("report.generated"),
argThat(map -> map.containsKey("reportType") && map.get("reportType").equals("sales"))
);
// Verify timestamp argument is recent
verifyStatic(MetricsCollector.class);
MetricsCollector.recordTimestamp(
argThat(timestamp -> timestamp.isAfter(LocalDateTime.now().minusMinutes(1)))
);
}Static verification works seamlessly with standard Mockito verification patterns:
@Test
@PrepareForTest(AuditLogger.class)
public void testMixedVerification() {
mockStatic(AuditLogger.class);
UserRepository mockRepo = mock(UserRepository.class);
UserService service = new UserService(mockRepo);
service.createUser("john.doe", "john@example.com");
// Verify instance method call
verify(mockRepo).save(any(User.class));
// Verify static method call
verifyStatic(AuditLogger.class);
AuditLogger.logUserCreation("john.doe");
// Combined verification with timing
verify(mockRepo, timeout(1000)).save(any(User.class));
verifyStatic(AuditLogger.class, timeout(1000));
AuditLogger.logUserCreation("john.doe");
}⚠️ These methods are deprecated and will be removed in PowerMock 2.0:
static void verifyStatic();
static void verifyStatic(VerificationMode verificationMode);These methods do not specify which class to verify, making them ambiguous in tests with multiple static mocks. Use the class-specific variants instead:
// Deprecated - avoid
verifyStatic();
FileUtils.readFile("test.txt");
// Recommended - explicit class specification
verifyStatic(FileUtils.class);
FileUtils.readFile("test.txt");mockStatic() before verification@PrepareForTest annotation@RunWith(PowerMockRunner.class) or equivalentInstall with Tessl CLI
npx tessl i tessl/maven-org-powermock--powermock-api-mockito