CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-powermock--powermock-api-mockito2

PowerMock API for Mockito 2.+ that enables advanced mocking of static methods, constructors, final classes and private methods through bytecode manipulation.

Pending
Overview
Eval results
Files

mock-creation.mddocs/

Mock Creation and Static Mocking

PowerMock's mock creation capabilities extend beyond standard Mockito to support final classes, static methods, and advanced spying scenarios. This comprehensive system handles traditionally challenging mocking scenarios through bytecode manipulation.

Mock Creation

Basic Mock Creation

Create mocks that support final and native methods that standard Mockito cannot handle.

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

Creates a mock object with default behavior for the specified type.

Usage Example:

// Mock a final class
FinalClass mockFinal = mock(FinalClass.class);
when(mockFinal.someMethod()).thenReturn("mocked");

// Mock works even with final methods
String result = mockFinal.someMethod();
assertEquals("mocked", result);

Mock with Custom Answer

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

Creates a mock with a specified default answer strategy for unstubbed method calls.

Parameters:

  • classToMock - The class or interface to mock
  • defaultAnswer - Default answer for unstubbed methods (e.g., RETURNS_SMART_NULLS, CALLS_REAL_METHODS)

Usage Example:

import static org.mockito.Mockito.RETURNS_SMART_NULLS;

MyClass mock = mock(MyClass.class, RETURNS_SMART_NULLS);
// Unstubbed methods will return smart nulls instead of null

Mock with Settings

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

Creates a mock with custom mock settings for advanced configuration.

Parameters:

  • classToMock - The class or interface to mock
  • mockSettings - Configuration settings created with Mockito.withSettings()

Usage Example:

import static org.mockito.Mockito.withSettings;

UserService mock = mock(UserService.class, 
    withSettings()
        .name("userServiceMock")
        .defaultAnswer(RETURNS_SMART_NULLS)
        .serializable());

Static Mocking

Basic Static Mocking

Enable static method mocking for one or more classes.

public static void mockStatic(Class<?> type, Class<?>... types);

Enables static mocking for the specified classes. Once enabled, all static methods become mockable.

Parameters:

  • type - Primary class to enable static mocking for
  • types - Additional classes to enable static mocking for (varargs)

Usage Example:

// Enable static mocking for utility classes
mockStatic(FileUtils.class, StringUtils.class);

// Now static methods can be stubbed
when(FileUtils.readFile("test.txt")).thenReturn("file content");
when(StringUtils.isEmpty(anyString())).thenReturn(false);

// Use the mocked static methods
String content = FileUtils.readFile("test.txt");
boolean empty = StringUtils.isEmpty("test");

assertEquals("file content", content);
assertFalse(empty);

Static Mocking with Answer

public static void mockStatic(Class<?> classMock, Answer defaultAnswer);

Enables static mocking with a custom default answer for unstubbed static methods.

Usage Example:

mockStatic(MathUtils.class, RETURNS_SMART_NULLS);
// Unstubbed static methods will return smart nulls

Static Mocking with Settings

public static void mockStatic(Class<?> classToMock, MockSettings mockSettings);

Enables static mocking with custom mock settings.

Usage Example:

mockStatic(Logger.class, 
    withSettings()
        .name("loggerMock")
        .defaultAnswer(CALLS_REAL_METHODS));

Spying

Object Spying

Spy on objects that are final or otherwise not "spyable" with standard Mockito.

public static <T> T spy(T object);

Creates a spy of the given object, allowing partial mocking where some methods can be stubbed while others call the real implementation.

Parameters:

  • object - The object to spy on

Usage Example:

List<String> realList = new ArrayList<>();
realList.add("original");

List<String> spyList = spy(realList);

// Stub specific methods
when(spyList.size()).thenReturn(100);

// Real methods still work
spyList.add("new item");

assertEquals(100, spyList.size()); // stubbed
assertTrue(spyList.contains("new item")); // real method

Class Spying

Create a spy for an entire class, enabling static method spying.

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

Enables spying on static methods of the specified class. Similar to static mocking but calls real methods by default.

Parameters:

  • type - The class to enable spying for

Usage Example:

spy(DatabaseUtils.class);

// Spy on specific static methods while leaving others unchanged
doReturn("mocked connection").when(DatabaseUtils.class);
DatabaseUtils.getConnection();

// Verify static method calls
verifyStatic(DatabaseUtils.class);
DatabaseUtils.getConnection();

Advanced Usage Patterns

Combining Mock Types

// Create regular mock
UserService userService = mock(UserService.class);

// Enable static mocking  
mockStatic(SecurityUtils.class);

// Create spy for partial mocking
OrderProcessor processor = spy(new OrderProcessor());

// Use all together
when(userService.getUser(1L)).thenReturn(testUser);
when(SecurityUtils.hasPermission(anyString())).thenReturn(true);
doNothing().when(processor).logOrder(any());

Mock Settings Combinations

DatabaseService dbMock = mock(DatabaseService.class,
    withSettings()
        .name("dbServiceMock")
        .defaultAnswer(RETURNS_SMART_NULLS)
        .extraInterfaces(Closeable.class)
        .serializable());

Error Handling

PowerMock mock creation may throw ClassNotPreparedException if the class hasn't been properly prepared for mocking:

try {
    mockStatic(SomeUtility.class);
} catch (ClassNotPreparedException e) {
    // Class wasn't prepared for mocking - check @PrepareForTest annotation
    fail("Class not prepared for mocking: " + e.getMessage());
}

Install with Tessl CLI

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

docs

expectations.md

index.md

mock-creation.md

stubbing.md

verification.md

tile.json