Mockito Frequently Asked Questions

Basic Questions

What is the difference between Mockito and PowerMock

Mockito is primarily used for mocking regular objects, while PowerMock can mock static methods, constructors, private methods, and more. However, PowerMock uses bytecode manipulation techniques that break test isolation, making tests closer to integration tests rather than unit tests. The official recommendation is to prefer Mockito first, and only consider PowerMock when Mockito truly cannot handle certain scenarios like mocking static methods. Since Mockito 2.x, static method mocking is also supported through mockito-inline.

When should I use Spy instead of Mock

Use Spy when you need most of the real behavior but want to mock only a few methods. Spy retains most of the real object's functionality while allowing specific methods to be stubbed. Mock completely replaces the real object, so no real method logic is executed. Use Mock when you need full control over object behavior. In practice, Spy is used relatively infrequently because in most cases using real test objects or complete mocks satisfies the requirements.

Can Mockito be used for final classes and methods

Since Mockito 2.1.0, you can configure Mockito to mock final classes and methods. You need to add the mockito-inline dependency instead of mockito-core. The mockito-inline enables dynamic subclassing mechanism to handle final classes and methods. This feature greatly enhances Mockito's applicability, making almost any Java class mockable.

Why do mock object methods return null

By default, all methods of mock objects return null or default values for their types (int returns 0, boolean returns false, collection types return empty collections, etc.). This is Mockito's default Answer behavior. If you need specific return values, you must explicitly set them using when().thenReturn().

Usage Questions

@Mock annotation is not working, what should I do

The @Mock annotation requires initializing the Mockito framework before it takes effect. Ensure you use one of MockitoAnnotations.initMocks(this), @RunWith(MockitoJUnitRunner.class), or @ExtendWith(MockitoExtension.class) (for JUnit 5) in your tests. If initialized correctly, @Mock annotated fields will automatically create mock objects before test methods execute.

How to mock void methods

For methods with void return type, use doThrow(), doAnswer(), or doNothing() to define behavior.

doThrow(new RuntimeException("Error")).when(mockedObject).voidMethod();
doAnswer(invocation -> null).when(mockedObject).voidMethod();
doNothing().when(mockedObject).voidMethod();

How to verify method call arguments

You can use argument matchers for verification, or use ArgumentCaptor to capture arguments for detailed assertions.

verify(mockedList).add(anyString());

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(mockedList).add(captor.capture());
assertTrue(captor.getValue().length() > 0);

How to mock iterators

Mocking iterators requires attention to the coordination between hasNext() and next() methods.

Iterator<String> mockIterator = mock(Iterator.class);
when(mockIterator.hasNext()).thenReturn(true, true, false);
when(mockIterator.next()).thenReturn("first", "second");

assertTrue(mockIterator.hasNext());
assertEquals("first", mockIterator.next());
assertTrue(mockIterator.hasNext());
assertEquals("second", mockIterator.next());
assertFalse(mockIterator.hasNext());

How to handle method overloading

When a class has overloaded methods, Mockito distinguishes different methods based on parameter types and counts. Ensure the parameter types in when() exactly match the method signature you want to mock.

when(mockedList.get(0)).thenReturn("string");      // get(int index)
when(mockedList.get(anyInt())).thenReturn("any"); // overloaded method

Advanced Questions

Why does when().thenReturn() not work

Common reasons include: setting behavior on the same method multiple times (only the last one takes effect); using Spy and calling the real method; method returns void (should use doReturn().when()); argument matcher used incorrectly causing match failure. Check your code to ensure the syntax for behavior setting is correct.

How to test abstract classes

When testing abstract classes, you can either mock concrete methods of the abstract class using Mockito, or use Spy to retain some real behavior. Another approach is to create a concrete test subclass to run tests.

@Test
public void testAbstractClass() {
    AbstractClass mock = mock(AbstractClass.class, Mockito.CALLS_REAL_METHODS);
    when(mock.concreteMethod()).thenReturn("mocked");
}

How to mock generic methods

When mocking generic methods, be aware of the limitations caused by type erasure. Use any() or anyObject() to match generic parameters.

when(mockedObject.genericMethod(any())).thenReturn("result");

How to verify call order

Use InOrder to verify that method calls are executed in a specific order.

InOrder inOrder = inOrder(mockedList);
inOrder.verify(mockedList).add("first");
inOrder.verify(mockedList).add("second");

How to partially mock objects

Use Spy for partial mocking, or use withSettings() to customize Mock behavior.

MyClass spy = spy(new MyClass());
doReturn("mocked").when(spy).method();

Performance Questions

Tests run slowly, what should I do

Ensure you are not using unnecessary real method calls. Check if you are creating new Mock objects in every test. For projects using a lot of Mockito, consider using @RunWith(MockitoJUnitRunner.Silent.class) to reduce log output.

How to reduce memory usage of Mock objects

Mockito's mock objects themselves do not consume much memory. However, if creating a large number of mock objects still affects performance, consider using @Mock annotation with @Scope to reuse mock objects, or use static mock factory methods.

Debugging Questions

How to view mock object call logs

You can use Mockito's logging feature or add listeners to track calls.

Mockito.framework().addListener(new VerificationListener());

Or use Maven/Gradle test output to view detailed mock call information.

How to debug when tests fail

Mockito provides detailed error messages. Check the differences between expected and actual calls shown in verify failures. Use Print Mockito Logs feature to understand mock object behavior. Simplify test cases step by step to locate problems.