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

constructor-mocking.mddocs/

Constructor and New Object Mocking

PowerMock's constructor mocking capabilities enable controlling object instantiation during testing. This is essential for testing code that creates objects internally, depends on specific constructor behavior, or needs to avoid expensive object creation.

Capabilities

Basic Constructor Expectations

Set up expectations for constructor calls with automatic parameter matching.

/**
 * Allows specifying expectations on new invocations.
 * 
 * @param type the class type being constructed
 * @param arguments the constructor arguments
 * @return expectation setter for further configuration
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Object... arguments) throws Exception;

/**
 * Allows specifying expectations on new invocations with explicit parameter types.
 * 
 * @param type the class type being constructed
 * @param parameterTypes the constructor parameter types
 * @param arguments the constructor arguments
 * @return expectation setter for further configuration
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception;

/**
 * Allows specifying expectations on new invocations using fully qualified class name.
 * 
 * @param fullyQualifiedName the fully qualified class name being constructed
 * @param arguments the constructor arguments
 * @return expectation setter for further configuration
 * @throws Exception if class cannot be found or constructor cannot be invoked
 */
public static synchronized <T> IExpectationSetters<T> expectNew(String fullyQualifiedName, Object... arguments) throws Exception;

Usage Example

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

@PrepareForTest({DatabaseService.class}) // Prepare the class that creates new objects
public class ConstructorMockingTest {
    
    @Test
    public void testConstructorMocking() throws Exception {
        // Create a mock to return instead of real object
        DatabaseConnection mockConnection = PowerMock.createMock(DatabaseConnection.class);
        
        // Set up constructor expectation
        PowerMock.expectNew(DatabaseConnection.class, "localhost", 5432)
                .andReturn(mockConnection);
        
        // Set up mock behavior
        expect(mockConnection.connect()).andReturn(true);
        expect(mockConnection.executeQuery("SELECT 1")).andReturn("result");
        
        PowerMock.replayAll();
        
        // Test code that creates new DatabaseConnection("localhost", 5432)
        DatabaseService service = new DatabaseService();
        String result = service.testConnection(); // Internally creates DatabaseConnection
        
        assertEquals("Connection successful: result", result);
        PowerMock.verifyAll();
    }
}

Constructor Expectations for Overloaded Constructors

Handle classes with multiple constructors by specifying exact parameter types.

@Test
public void testOverloadedConstructors() throws Exception {
    FileProcessor mockProcessor = PowerMock.createMock(FileProcessor.class);
    
    // Specify exact constructor signature for overloaded constructors
    Class<?>[] paramTypes = {String.class, boolean.class, int.class};
    PowerMock.expectNew(FileProcessor.class, paramTypes, "input.txt", true, 1024)
            .andReturn(mockProcessor);
    
    expect(mockProcessor.process()).andReturn("processed");
    PowerMock.replayAll();
    
    // Code that creates: new FileProcessor("input.txt", true, 1024)
    DocumentHandler handler = new DocumentHandler();
    String result = handler.processDocument("input.txt");
    
    assertEquals("processed", result);
    PowerMock.verifyAll();
}

Strict Constructor Expectations

Set up strict constructor expectations that verify the order of object creation.

/**
 * Allows specifying strict expectations on new invocations.
 * 
 * @param type the class type being constructed
 * @param arguments the constructor arguments
 * @return expectation setter for further configuration
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> IExpectationSetters<T> expectStrictNew(Class<T> type, Object... arguments) throws Exception;

/**
 * Allows specifying strict expectations on new invocations with explicit parameter types.
 * 
 * @param type the class type being constructed
 * @param parameterTypes the constructor parameter types
 * @param arguments the constructor arguments
 * @return expectation setter for further configuration
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> IExpectationSetters<T> expectStrictNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception;

Usage Example

@Test
public void testStrictConstructorOrder() throws Exception {
    Logger mockLogger = PowerMock.createMock(Logger.class);
    Metrics mockMetrics = PowerMock.createMock(Metrics.class);
    
    // Strict expectations verify constructor call order
    PowerMock.expectStrictNew(Logger.class, "application.log").andReturn(mockLogger);
    PowerMock.expectStrictNew(Metrics.class, mockLogger).andReturn(mockMetrics);
    
    PowerMock.replayAll();
    
    // These constructor calls must happen in exactly this order
    ApplicationService service = new ApplicationService(); // Creates Logger first, then Metrics
    
    PowerMock.verifyAll();
}

Nice Constructor Expectations

Set up lenient constructor expectations that allow unexpected constructor calls.

/**
 * Allows specifying nice expectations on new invocations.
 * 
 * @param type the class type being constructed
 * @param arguments the constructor arguments
 * @return expectation setter for further configuration
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> IExpectationSetters<T> expectNiceNew(Class<T> type, Object... arguments) throws Exception;

/**
 * Allows specifying nice expectations on new invocations with explicit parameter types.
 * 
 * @param type the class type being constructed
 * @param parameterTypes the constructor parameter types
 * @param arguments the constructor arguments
 * @return expectation setter for further configuration
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> IExpectationSetters<T> expectNiceNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception;

Usage Example

@Test
public void testNiceConstructorExpectations() throws Exception {
    ConfigManager mockConfig = PowerMock.createMock(ConfigManager.class);
    
    // Nice expectation allows unexpected constructor calls
    PowerMock.expectNiceNew(ConfigManager.class, "app.properties").andReturn(mockConfig);
    
    PowerMock.replayAll();
    
    // This constructor call is expected
    ConfigManager config1 = new ConfigManager("app.properties");
    
    // These constructor calls are not explicitly expected but allowed with nice mock
    ConfigManager config2 = new ConfigManager("other.properties");  // Returns null by default
    ConfigManager config3 = new ConfigManager();  // Returns null by default
    
    PowerMock.verifyAll();
}

Convenience Methods for Mock and Expect

Combine mock creation with constructor expectation in a single method call.

/**
 * Convenience method for createMock followed by expectNew.
 * 
 * @param type the class that should be mocked
 * @param arguments the constructor arguments
 * @return a mock object of the same type
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> T createMockAndExpectNew(Class<T> type, Object... arguments) throws Exception;

/**
 * Convenience method for createMock followed by expectNew with parameter types.
 * 
 * @param type the class that should be mocked
 * @param parameterTypes the constructor parameter types
 * @param arguments the constructor arguments
 * @return a mock object of the same type
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> T createMockAndExpectNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception;

/**
 * Convenience method for createStrictMock followed by expectNew.
 * 
 * @param type the class that should be mocked
 * @param arguments the constructor arguments
 * @return a mock object of the same type
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> T createStrictMockAndExpectNew(Class<T> type, Object... arguments) throws Exception;

/**
 * Convenience method for createNiceMock followed by expectNew.
 * 
 * @param type the class that should be mocked
 * @param arguments the constructor arguments
 * @return a mock object of the same type
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> T createNiceMockAndExpectNew(Class<T> type, Object... arguments) throws Exception;

Usage Example

@Test
public void testConvenienceMethods() throws Exception {
    // One-liner to create mock and set up constructor expectation
    EmailService mockEmailService = PowerMock.createMockAndExpectNew(
        EmailService.class, "smtp.example.com", 587);
    
    expect(mockEmailService.sendEmail("test@example.com", "Subject", "Body"))
        .andReturn(true);
    
    PowerMock.replayAll();
    
    // Code that creates new EmailService("smtp.example.com", 587)
    NotificationManager manager = new NotificationManager();
    boolean sent = manager.sendNotification("test@example.com", "Subject", "Body");
    
    assertTrue(sent);
    PowerMock.verifyAll();
}

Inner and Anonymous Class Support

Mock constructor calls for inner classes, local classes, and anonymous classes using fully qualified names.

/**
 * Allows specifying expectations on new invocations for private member classes.
 * 
 * @param fullyQualifiedName the fully-qualified name of the inner/local/anonymous type
 * @param arguments the constructor arguments
 * @return expectation setter for further configuration
 * @throws Exception if constructor cannot be found or invoked
 */
public static synchronized <T> IExpectationSetters<T> expectNew(String fullyQualifiedName, Object... arguments) throws Exception;

Usage Example

@Test
public void testInnerClassConstructor() throws Exception {
    // Mock inner class constructor using fully qualified name
    PowerMock.expectNew("com.example.OuterClass$InnerClass", "parameter")
            .andReturn(mockInnerInstance);
    
    PowerMock.replayAll();
    
    // Code that creates new OuterClass.InnerClass("parameter")
    OuterClass outer = new OuterClass();
    outer.createInnerInstance("parameter");
    
    PowerMock.verifyAll();
}

Important Notes

PrepareForTest Requirements

The class that contains the new statement (not the class being constructed) must be prepared for testing:

// If MyService creates new DatabaseConnection(), prepare MyService
@PrepareForTest({MyService.class})
public class MyTest {
    @Test
    public void test() throws Exception {
        PowerMock.expectNew(DatabaseConnection.class, "localhost").andReturn(mock);
        // ...
    }
}

Exception Handling

Constructor expectations can throw exceptions instead of returning mocks:

PowerMock.expectNew(DatabaseConnection.class, "invalid-host")
        .andThrow(new ConnectionException("Cannot connect to invalid-host"));

Multiple Constructor Calls

Handle multiple calls to the same constructor with different expectations:

PowerMock.expectNew(TempFile.class).andReturn(mockFile1);
PowerMock.expectNew(TempFile.class).andReturn(mockFile2);
PowerMock.expectNew(TempFile.class).andThrow(new IOException("Disk full"));

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