CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-powermock--powermock-api-easymock

PowerMock API extension for EasyMock providing advanced mocking capabilities for static methods, constructors, final classes, and private methods through bytecode manipulation.

Pending
Overview
Eval results
Files

static-mocking.mddocs/

Static Method Mocking

PowerMock's static method mocking capabilities enable testing of code that depends on static method calls. This is essential for testing legacy code, third-party libraries, and system interactions that rely on static APIs.

Capabilities

Basic Static Mocking

Enable mocking for all static methods in a class or specific static methods only.

/**
 * Enable static mocking for a class.
 * 
 * @param type the class to enable static mocking
 * @param methods optionally what methods to mock
 */
public static synchronized void mockStatic(Class<?> type, Method... methods);

/**
 * Enable static mocking for a class.
 * 
 * @param type the class to enable static mocking
 */
public static synchronized void mockStatic(Class<?> type);

Usage Example

import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import static org.easymock.EasyMock.expect;

@PrepareForTest({SystemUtils.class})
public class StaticMockingTest {
    
    @Test
    public void testStaticMethod() {
        // Mock all static methods in SystemUtils
        PowerMock.mockStatic(SystemUtils.class);
        expect(SystemUtils.getCurrentUser()).andReturn("testuser");
        expect(SystemUtils.getSystemProperty("os.name")).andReturn("TestOS");
        PowerMock.replayAll();
        
        // Test code that calls static methods
        String user = MyApplication.getCurrentUserInfo();
        assertEquals("User: testuser on TestOS", user);
        
        PowerMock.verifyAll();
    }
}

Strict Static Mocking

Enable strict static mocking that verifies the order of static method calls.

/**
 * Enable strict static mocking for a class.
 * 
 * @param type the class to enable static mocking
 * @param methods optionally what methods to mock
 */
public static synchronized void mockStaticStrict(Class<?> type, Method... methods);

/**
 * Enable strict static mocking for a class.
 * 
 * @param type the class to enable static mocking
 */
public static synchronized void mockStaticStrict(Class<?> type);

Usage Example

@Test
public void testStaticMethodOrder() {
    PowerMock.mockStaticStrict(FileUtils.class);
    expect(FileUtils.createTempDirectory()).andReturn("/tmp/test");
    expect(FileUtils.writeFile("/tmp/test/data.txt", "content")).andReturn(true);
    expect(FileUtils.deleteDirectory("/tmp/test")).andReturn(true);
    PowerMock.replayAll();
    
    // These static calls must happen in exactly this order
    String tempDir = FileUtils.createTempDirectory();
    FileUtils.writeFile(tempDir + "/data.txt", "content");
    FileUtils.deleteDirectory(tempDir);
    
    PowerMock.verifyAll();
}

Nice Static Mocking

Enable nice static mocking that provides default return values for unexpected static method calls.

/**
 * Enable nice static mocking for a class.
 * 
 * @param type the class to enable static mocking
 * @param methods optionally what methods to mock
 */
public static synchronized void mockStaticNice(Class<?> type, Method... methods);

/**
 * Enable nice static mocking for a class.
 * 
 * @param type the class to enable static mocking
 */
public static synchronized void mockStaticNice(Class<?> type);

Usage Example

@Test
public void testNiceStaticMocking() {
    PowerMock.mockStaticNice(MathUtils.class);
    // Only set up the static methods you care about
    expect(MathUtils.square(5)).andReturn(25);
    PowerMock.replayAll();
    
    // This call has explicit expectation
    int result = MathUtils.square(5);  // Returns 25
    assertEquals(25, result);
    
    // These calls don't have expectations but work with nice mock
    double pi = MathUtils.getPi();        // Returns 0.0 (default for double)
    boolean isEven = MathUtils.isEven(4); // Returns false (default for boolean)
    
    PowerMock.verifyAll();
}

Partial Static Mocking

Mock specific static methods by name, leaving other static methods with their original behavior.

/**
 * Mock several static methods by name.
 * 
 * @param clazz the class that contains the static methods
 * @param methodNames the names of the methods that should be mocked
 */
public static synchronized void mockStaticPartial(Class<?> clazz, String... methodNames);

/**
 * Mock several static methods (strict) by name.
 * 
 * @param clazz the class that contains the static methods
 * @param methodNames the names of the methods that should be mocked
 */
public static synchronized void mockStaticPartialStrict(Class<?> clazz, String... methodNames);

/**
 * Mock several static methods (nice) by name.
 * 
 * @param clazz the class that contains the static methods
 * @param methodNames the names of the methods that should be mocked
 */
public static synchronized void mockStaticPartialNice(Class<?> clazz, String... methodNames);

Usage Example

@Test
public void testPartialStaticMocking() {
    // Only mock specific static methods by name
    PowerMock.mockStaticPartial(DateUtils.class, "getCurrentTimestamp", "formatDate");
    
    expect(DateUtils.getCurrentTimestamp()).andReturn(1234567890L);
    expect(DateUtils.formatDate(anyObject(Date.class))).andReturn("2023-01-01");
    PowerMock.replayAll();
    
    // Mocked static methods
    long timestamp = DateUtils.getCurrentTimestamp();  // Returns 1234567890L
    String formatted = DateUtils.formatDate(new Date()); // Returns "2023-01-01"
    
    // Non-mocked static methods retain original behavior
    Date parsed = DateUtils.parseDate("2023-01-01");  // Uses real implementation
    
    PowerMock.verifyAll();
}

Specific Static Method Mocking

Mock specific static methods with parameter type specification for overloaded methods.

/**
 * Mock a single static method.
 * 
 * @param clazz the class where the method is specified
 * @param methodNameToMock the method name to mock
 * @param firstArgumentType the first argument type
 * @param additionalArgumentTypes optional additional argument types
 */
public static synchronized void mockStaticPartial(Class<?> clazz, String methodNameToMock,
                                                  Class<?> firstArgumentType, Class<?>... additionalArgumentTypes);

/**
 * Mock a single static method (strict).
 * 
 * @param clazz the class where the method is specified
 * @param methodNameToMock the method name to mock
 * @param firstArgumentType the first argument type
 * @param additionalArgumentTypes optional additional argument types
 */
public static synchronized void mockStaticPartialStrict(Class<?> clazz, String methodNameToMock,
                                                        Class<?> firstArgumentType, Class<?>... additionalArgumentTypes);

/**
 * Mock a single static method (nice).
 * 
 * @param clazz the class where the method is specified
 * @param methodNameToMock the method name to mock
 * @param firstArgumentType the first argument type
 * @param additionalArgumentTypes optional additional argument types
 */
public static synchronized void mockStaticPartialNice(Class<?> clazz, String methodNameToMock,
                                                      Class<?> firstArgumentType, Class<?>... additionalArgumentTypes);

Usage Example

@Test
public void testOverloadedStaticMethods() {
    // Mock specific overloaded static method
    PowerMock.mockStaticPartial(StringUtils.class, "join", List.class, String.class);
    
    List<String> items = Arrays.asList("a", "b", "c");
    expect(StringUtils.join(items, ",")).andReturn("a,b,c");
    PowerMock.replayAll();
    
    // This overloaded version is mocked
    String result = StringUtils.join(items, ",");  // Returns "a,b,c"
    assertEquals("a,b,c", result);
    
    // Other overloaded versions retain original behavior
    String result2 = StringUtils.join(new String[]{"x", "y"}, "-");  // Uses real implementation
    
    PowerMock.verifyAll();
}

Important Notes

PrepareForTest Annotation

Classes with static methods being mocked must be specified in the @PrepareForTest annotation:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SystemUtils.class, FileUtils.class})
public class MyTest {
    // Static mocking tests
}

Replay and Verify

Static mocks must be included in replay and verify operations:

// Include the class in replay/verify
PowerMock.mockStatic(SystemUtils.class);
expect(SystemUtils.getProperty("key")).andReturn("value");
PowerMock.replay(SystemUtils.class);  // Replay the class, not instance

// Or use replayAll() to replay all mocks including static ones
PowerMock.replayAll();

Thread Safety

Static mocking affects the entire JVM class loading, so tests using static mocks should be run in isolation or with careful coordination to avoid interference between tests.

Install with Tessl CLI

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

docs

annotations.md

constructor-mocking.md

core-mocking.md

index.md

mock-control.md

partial-mocking.md

private-methods.md

reflection.md

static-mocking.md

tile.json