W3docs

Use Mockito to mock some methods but not others

Mockito is a Java mocking framework that allows you to create mock objects for testing.

Mockito is a Java mocking framework that allows you to create mock objects for testing. You can use Mockito to mock some methods of an object but not others by using the following steps:

First, ensure you have the necessary static imports and a sample class:

import static org.mockito.Mockito.*;

public class MyObject {
    public int getValue() { return 0; }
    public String getString() { return "Real"; }
    public void doSomething() { System.out.println("Real implementation"); }
}
  1. Create a spy of the object using Mockito.spy(). This is the idiomatic approach for partial mocking. Unlike pure mocks (which return null or 0 for unstubbed methods), spies automatically delegate unstubbed methods to the real implementation:
MyObject realObject = new MyObject();
MyObject spy = spy(realObject);
  1. Use Mockito.when() to specify the behavior of the spy for the methods that you want to mock:
when(spy.getValue()).thenReturn(10);
when(spy.getString()).thenReturn("Mocked");
  1. Leave other methods unstubbed; the spy will automatically call the real implementation:
spy.doSomething(); // calls the real implementation
  1. Use the spy object in your test as you would any other object:
int result = spy.getValue();  // returns 10
String str = spy.getString(); // returns "Mocked"
spy.doSomething();            // calls the real implementation

Keep in mind that partial mocking is generally discouraged by the Mockito team, as it can lead to fragile and untestable code. Use it sparingly, and only for isolated units of code where refactoring is not feasible.