ReviseAlgo Logo

Testing in Java

Mocking with Mockito

Learn how to isolate your unit tests from heavy dependencies using mock objects and verification steps.

Interview: Highly relevant for software engineer positions. Expect questions on Mocks vs Spies, argument capturing, stubbing void methods, and avoiding over-mocking.

Last Updated: June 13, 2026 10 min read

Mockito is the standard library used to simulate class behaviors and isolate the class under test (SUT) from database connectors, REST clients, and heavy sub-systems.

Core Idea

Mocks are dummy implementations that return default/pre-stubbed values. Spies are partial mocks wraps real objects.

Why It Matters

Without mocking, a single unit test requires configuring real network connections, filesystem paths, and database transactions.

Interview Lens

Tricky questions examine stubbing void methods (doThrow/doAnswer vs when/thenReturn) and verifying invocation counts.

Mock vs Spy

A Mock creates an empty shell where all method calls are intercepted and return default values (e.g. null, 0, or false) unless explicitly stubbed. A Spy wrap a real, living instance; method calls delegate to the actual implementation unless stubbed. Spies are useful for legacy code test integrations.

Code Walkthrough

This class demonstrates injecting mock objects, stubbing values, and verifying interactions.

Interview-Relevant Information

Q: How do you mock or stub a void method to throw an exception?
Answer: Since void methods do not return values, the when(...) construct fails at compile-time. Instead, use Mockito's doThrow(Throwable) or doAnswer(Answer) methods. For example: doThrow(new RuntimeException()).when(mockObject).voidMethod();.

Q: What is the risk of over-mocking?
Answer: Mocking implementation details instead of system behavior links your tests directly to class structural configurations. A minor internal refactoring that does not change functional behavior will break over-mocked tests, creating high maintenance overhead.

Quick Checklist

Can you distinguish between @Mock and @Spy? Do you know when to use ArgumentCaptor to assert nested payloads? If yes, you can isolate components effectively.

Use Cases

Isolating business services from database operations during quick unit tests.

Simulating HTTP failures or network timeouts on API integrations to test fallback mechanisms.

Common Mistakes

Using when() syntax on a spy's real method which executes the actual method block (causing unwanted side effects). Use doReturn() instead.

Attempting to mock final classes or final methods without enabling Mockito's inline mockmaker plugin.