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

object-mocking.mddocs/

Enhanced Object Mocking

PowerMock extends Mockito's object mocking capabilities to handle final classes, final methods, and native methods that cannot be mocked with standard Mockito. This enables comprehensive testing of legacy code without requiring architectural changes.

Capabilities

Basic Enhanced Mocking

Create mocks of classes that cannot be mocked with standard Mockito, including final classes and classes with final methods.

static <T> T mock(Class<T> type);

Parameters:

  • type - The class to mock (can be final)

Returns: Mock instance of the specified type

Usage Example:

@Test
@PrepareForTest(FinalClass.class)
public void testFinalClassMocking() {
    FinalClass mock = mock(FinalClass.class);
    when(mock.getValue()).thenReturn("mocked value");
    
    String result = mock.getValue();
    assertEquals("mocked value", result);
    
    verify(mock).getValue();
}

Mocking with Custom Answer

Create enhanced mocks with a custom default answer strategy for unstubbed method calls.

static <T> T mock(Class<T> classToMock, Answer defaultAnswer);

Parameters:

  • classToMock - The class to mock
  • defaultAnswer - Default answer strategy for unstubbed methods

Returns: Mock instance with custom default behavior

Usage Example:

@Test
@PrepareForTest(ServiceClass.class)
public void testMockWithCustomAnswer() {
    ServiceClass mock = mock(ServiceClass.class, RETURNS_SMART_NULLS);
    
    // Only stub specific method
    when(mock.getImportantValue()).thenReturn("important");
    
    String important = mock.getImportantValue(); // Returns "important"
    String other = mock.getOtherValue(); // Returns smart null
}

Mocking with Settings

Create enhanced mocks with advanced MockSettings configuration for specialized testing scenarios.

static <T> T mock(Class<T> classToMock, MockSettings mockSettings);

Parameters:

  • classToMock - The class to mock
  • mockSettings - Advanced mock configuration

Returns: Mock instance configured with specified settings

Usage Example:

@Test
@PrepareForTest(ComplexService.class)
public void testMockWithSettings() {
    ComplexService mock = mock(ComplexService.class,
        withSettings()
            .name("ComplexServiceMock")
            .defaultAnswer(RETURNS_DEEP_STUBS)
            .extraInterfaces(Serializable.class));
    
    when(mock.getConfiguration().getProperty("key")).thenReturn("value");
    
    String property = mock.getConfiguration().getProperty("key");
    assertEquals("value", property);
}

Enhanced Spying on Objects

Spy on objects that are final or otherwise not "spyable" with standard Mockito, enabling partial mocking of real objects.

static <T> T spy(T object);

Parameters:

  • object - The real object to spy on (can be final)

Returns: Spy instance that delegates to the real object unless stubbed

Usage Example:

@Test
@PrepareForTest(FinalService.class)
public void testSpyOnFinalObject() {
    FinalService realService = new FinalService();
    FinalService spy = spy(realService);
    
    // Stub one method, others call real implementation
    when(spy.getValue()).thenReturn("spied value");
    
    String value = spy.getValue(); // Returns "spied value"
    String realResult = spy.calculateSomething(); // Calls real method
    
    verify(spy).getValue();
    verify(spy).calculateSomething();
}

Enhanced Class Spying

Enable spying on static methods of a class, allowing partial mocking of static behavior.

static <T> void spy(Class<T> type);

Parameters:

  • type - The class to enable static spying for

Usage Example:

@Test  
@PrepareForTest(UtilityClass.class)
public void testSpyOnClass() {
    spy(UtilityClass.class);
    
    // Stub one static method, others call real implementation
    when(UtilityClass.getValue()).thenReturn("spied static value");
    
    String value = UtilityClass.getValue(); // Returns "spied static value"
    int realResult = UtilityClass.calculate(5, 3); // Calls real method
    
    verifyStatic(UtilityClass.class);
    UtilityClass.getValue();
}

Common Patterns

Testing Final Third-Party Classes

@Test
@PrepareForTest(HttpURLConnection.class)
public void testFinalThirdPartyClass() {
    HttpURLConnection connection = mock(HttpURLConnection.class);
    when(connection.getResponseCode()).thenReturn(200);
    when(connection.getInputStream()).thenReturn(new ByteArrayInputStream("response".getBytes()));
    
    // Test code that uses the mocked connection
    MyHttpClient client = new MyHttpClient();
    String response = client.makeRequest(connection);
    
    assertEquals("response", response);
    verify(connection).getResponseCode();
}

Partial Mocking of Legacy Objects

@Test
@PrepareForTest(LegacyService.class)
public void testPartialMocking() {
    LegacyService service = new LegacyService();
    LegacyService spy = spy(service);
    
    // Mock only the problematic dependency method
    when(spy.callExternalService()).thenReturn("mocked external response");
    
    // Test the main business logic with mocked dependency
    String result = spy.processData("input");
    
    // Verify the external call was made but returned mocked value
    verify(spy).callExternalService();
    assertTrue(result.contains("mocked external response"));
}

Mocking Classes with Native Methods

@Test
@PrepareForTest(SystemClass.class)
public void testNativeMethodMocking() {
    SystemClass mock = mock(SystemClass.class);
    
    // Mock native method that would normally fail in test environment
    when(mock.nativeSystemCall()).thenReturn("mocked native result");
    
    ApplicationService service = new ApplicationService(mock);
    service.performSystemOperation();
    
    verify(mock).nativeSystemCall();
}

Requirements

  • Final classes must be specified in @PrepareForTest annotation
  • Test must use @RunWith(PowerMockRunner.class) or equivalent
  • Enhanced mocking works with all standard Mockito verification and stubbing
  • Spies maintain real object behavior unless explicitly stubbed

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