Mockito
Mockito is a library that builds test doubles for Java interfaces and classes. You stub return values, verify calls, and keep the class under test away from the network and the database.
Detailed Explanation
A unit test of SignupService should not send email. You pass a mock Mailer. when(mailer.send(any(), any())).thenReturn(...) or, for void methods, doNothing().when(mailer).send(...). After the act, verify(mailer).send("a@b.com", "welcome") checks the collaboration.
Mockito uses proxies (subclass or interface). final classes and methods needed mockito-inline for a long time; recent Mockito versions mock finals by default on a modern JDK. static mocks exist and make tests brittle; prefer injecting a clock or a wrapper.
Good tests stub only what they need and verify the one interaction that is the point. verifyNoMoreInteractions is useful when extra calls are bugs. Argument captors record what was passed. eq, any, argThat match arguments. Mixing raw values and matchers in one call is illegal; use eq("a") with any().
You reach for Mockito when a collaborator is an interface you own and the interaction is the specification. You reach for a hand-written fake when the double has behaviour (an in-memory repo). You do not mock the class under test. You do not mock ArrayList.
The cost of a mock-heavy suite is tests that break when you rename a method and that pass when the real collaborator would throw. The cost of when(repo.find(1)).thenReturn(user) in every test is a fixture you should extract. The cost of mocking JPA entities is pain; use real objects.
@ExtendWith(MockitoExtension.class) and @Mock / @InjectMocks cut setup. @InjectMocks cannot do magic for two constructors; prefer explicit new Service(mock).
Code Examples
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
interface Mailer {
void send(String to, String body);
}
class Signup {
private final Mailer mailer;
Signup(Mailer mailer) {
this.mailer = mailer;
}
void welcome(String email) {
mailer.send(email, "welcome");
}
}
class SignupTest {
@Test
void sendsWelcome() {
Mailer mailer = Mockito.mock(Mailer.class);
new Signup(mailer).welcome("a@b.com");
Mockito.verify(mailer).send("a@b.com", "welcome");
}
}import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
interface Tax {
int add(int paise);
}
class TaxStub {
static Tax gst() {
Tax tax = org.mockito.Mockito.mock(Tax.class);
when(tax.add(org.mockito.ArgumentMatchers.anyInt())).thenAnswer(inv -> {
int p = inv.getArgument(0);
return p + p * 18 / 100;
});
return tax;
}
}Common Gotchas
Mixing raw arguments and matchers in one stub
use `eq` for the raw one.
Mocking the class under test tests the mock
inject doubles, do not mock `Signup`.
`static` mocks hide design problems
inject a `Clock` instead.
Void methods use `doThrow`/`doNothing`, not `when(...).then`
Void methods use `doThrow`/`doNothing`, not `when(...).then`