Is there a way to mock only specific methods in a class while keeping other methods real using doCallRealMethod() in Mockito?
I need to unit test a class that has a third-party dependency I cannot remove. Currently, I’ve mocked the entire class and used Mockito.doCallRealMethod() for all function calls, but this feels like it hides what’s actually happening.
I want the real class behavior for everything except a single method I want to mock.
How can I achieve this using doCallRealMethod() effectively?
Hey! I faced a similar issue recently. What worked for me was using a partial mock (spy) instead of mocking the whole class.
With a spy, the real methods are called by default, and you can override only the specific method you want.
For example:
MyClass myClassSpy = Mockito.spy(new MyClass());
Mockito.doReturn(mockedValue).when(myClassSpy).methodToMock();
Everything else behaves normally, and doCallRealMethod() isn’t needed for the rest since the spy calls real methods automatically.
This keeps your tests clean and focuses only on the method you want to mock.
I ran into the same problem and found that spying combined with doCallRealMethod() works nicely when you need more control.
You create a spy, then explicitly tell Mockito which methods should use real implementations:
MyClass myClassSpy = Mockito.spy(MyClass.class);
Mockito.doCallRealMethod().when(myClassSpy).methodToKeepReal();
Mockito.doReturn(mockValue).when(myClassSpy).methodToMock();
This way, you only mock the method you care about, and the rest still behaves like the actual class.
I felt this made my tests more predictable than mocking everything.
From my experience, the trick is to not mock the whole class at all. Instead, use a spy and selectively mock methods using doReturn() or doAnswer().
You only need doCallRealMethod() if you explicitly want to override the default spy behavior.
For instance:
MyClass spyClass = Mockito.spy(new MyClass());
Mockito.doReturn(customValue).when(spyClass).methodToMock();
All other methods run normally. I found this approach makes it easier to reason about tests since you’re not forcing doCallRealMethod() on everything, just the parts you care about.