How do you enable Mockito's @Mock and @InjectMocks annotations in a JUnit 5 test, and what alternatives exist?
answer
- @ExtendWith(MockitoExtension.class) on JUnit 5
- openMocks(this) in @BeforeEach, close in @AfterEach
- initMocks is deprecated → use openMocks
- Extension adds strict stubbing (UnnecessaryStubbingException)
- No processor → fields null → NPE
basics
~10 sAdd @ExtendWith(MockitoExtension.class) to the test class. Without it (or a manual MockitoAnnotations.openMocks(this) call in setup), the annotated fields stay null.
solid answer
~40 sThe annotations are inert metadata; something must process them. On JUnit 5 the idiomatic way is @ExtendWith(MockitoExtension.class) on the test class — it initialises all @Mock/@Spy/@InjectMocks fields before each test and adds strict-stubbing checks that fail the test on unused stubs. The manual alternative is MockitoAnnotations.openMocks(this) in an @BeforeEach method; it returns an AutoCloseable you should close in @AfterEach to release resources. The older initMocks(this) does the same but is deprecated. On JUnit 4 you instead use @RunWith(MockitoJUnitRunner.class) or a MockitoRule. If none of these is present, the mock fields are never created, so calling them throws NullPointerException. The extension is preferred because it requires no boilerplate setup method and enforces stricter, cleaner tests.
go deeper
Knows to put @ExtendWith(MockitoExtension.class) on the class so the mocks get created.
Can describe all three activation routes (extension, openMocks, JUnit 4 runner/rule), why fields are null without them, and that openMocks replaced initMocks.
Explains strict-stubbing semantics, the mockito-junit-jupiter dependency split, AutoCloseable cleanup, and when manual openMocks is justified over the extension.
Standardises the team on one activation style, weighs strict vs lenient stubbing policy for the codebase, and understands lifecycle/leak implications of the inline mock maker at scale.
## Why activation is needed Java annotations like `@Mock` are just **metadata** — they do nothing on their own. A separate component must scan the test instance, find the annotated fields, create the mocks, and perform `@InjectMocks` wiring. Until that runs, every `@Mock`/`@InjectMocks` field is `null`, and the first method call on it throws a `NullPointerException`. There are three ways to make it run, depending on your JUnit version. ## 1. JUnit 5 — MockitoExtension (recommended) ```java @ExtendWith(MockitoExtension.class) class OrderServiceTest { @Mock PaymentGateway gateway; @InjectMocks OrderService service; // ... } ``` `@ExtendWith` registers an **extension** — JUnit 5's plugin mechanism that hooks into the test lifecycle. `MockitoExtension` initialises the annotated fields **before each test method** and tears them down afterward. It comes from the `mockito-junit-jupiter` artifact (a separate dependency from core `mockito-core`). It also enables **strict stubbing** by default: if you stub a method with `when(...).thenReturn(...)` but the test never calls it, the test **fails** with `UnnecessaryStubbingException`. This catches dead stubs and copy-paste mistakes. You can relax it per-test with `@MockitoSettings(strictness = Strictness.LENIENT)` or `lenient().when(...)`. ## 2. Manual — MockitoAnnotations.openMocks If you cannot or do not want to use the extension: ```java class OrderServiceTest { @Mock PaymentGateway gateway; @InjectMocks OrderService service; private AutoCloseable mocks; @BeforeEach void setUp() { mocks = MockitoAnnotations.openMocks(this); } @AfterEach void tearDown() throws Exception { mocks.close(); } } ``` `openMocks(this)` scans the passed object (the test instance) and wires its annotations. It returns an `AutoCloseable`; closing it in `@AfterEach` releases internal references (relevant for inline mock makers and to avoid leaks across many tests). The older `MockitoAnnotations.initMocks(this)` does the same but is **deprecated** because it gave no handle to close. This manual route does **not** add strict-stubbing the way the extension does (default Mockito strictness is `WARN`). ## 3. JUnit 4 For legacy JUnit 4 tests: ```java @RunWith(MockitoJUnitRunner.class) public class OrderServiceTest { ... } ``` or the `@Rule public MockitoRule rule = MockitoJUnit.rule();` form (a rule composes more flexibly than a runner, since a class can have only one runner). ## Choosing - Prefer **MockitoExtension** on JUnit 5: zero setup boilerplate, automatic per-test reset, strict stubbing. - Use **openMocks** when you need a parameterised approach, are mixing frameworks, or must control lifecycle manually. - The two are mutually exclusive — using both double-initialises and can hide stubbing problems. ## Common failure Seeing an NPE on a `@Mock` field almost always means no processor ran — the test forgot `@ExtendWith(MockitoExtension.class)` or the `openMocks` call.
- What is UnnecessaryStubbingException and what triggers it?MockitoExtension's default strict stubbing throws it when a stub set up with when(...) is never actually exercised by the test, flagging a dead or misplaced stub.
- Why does openMocks return an AutoCloseable?So you can close it in @AfterEach to release Mockito's internal references to mocks, preventing leaks across many test instances (important with the inline mock maker).
saying these in an interview costs you the question
- Claiming the annotations work with no extension or openMocks call
- Using deprecated initMocks instead of openMocks
- Using both MockitoExtension AND openMocks together
- Thinking MockitoExtension comes from mockito-core (it's in mockito-junit-jupiter)