Lesson 42: Mocking Dependencies with Mockito

12 Aug 2026 1 min Swarnil Singhai

Mocking replaces a real dependency (like a database or external API) with a fake so you can test your logic in isolation, fast and deterministically.

Real-time example

Testing an OrderService shouldn't require a real payment gateway — Mockito fakes the gateway so the test runs in milliseconds, offline.

PaymentGateway mockGateway = mock(PaymentGateway.class);
when(mockGateway.charge(500.0)).thenReturn(true);

OrderService service = new OrderService(mockGateway);
boolean result = service.placeOrder(500.0);

assertTrue(result);
verify(mockGateway).charge(500.0);

What's happening

verify confirms charge was actually called with the right argument — testing not just the result, but the interaction.

Mock external systems (network, DB, time) at the boundary — don't mock the class you're actually trying to test.

Advertisement