Mockito.mock() vs @Mock Annotation
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
mock() and @Mock is how the mock gets created.
mock(), you call it directly in your code—usually in a test method or in the before-each setup—and it gives you a mock object right there. With @Mock, you declare the mock as a field with the annotation, and MockitoExtension automatically initializes it before your test runs.
You need to have @ExtendWith MockitoExtension at the class level for the @Mock annotation to work; otherwise, the field stays null and you'll get a NullPointerException when you try to use it. That's the most common mistake freshers make—putting @Mock on a field but forgetting the extension, and then being confused why the mock is null.
The annotation style is generally preferred in modern tests because it's cleaner and more declarative—you can see all your test dependencies right at the top of the class as annotated fields. It also gives you strict stubbing automatically, which catches bugs where you declare stubs that never get called.
mock() gives you more control and works in places where annotations don't, like inside parameterized tests or helper methods, but you lose the automatic lifecycle management and the strict stubbing safety net unless you configure that manually. mock() when you need the flexibility or you're working outside the JUnit test class structure.
Mockito.mock() vs @Mock Annotation
Direct Answer
Mockito.mock(Class.class) creates mocks programmatically, while @Mock is annotation-based and requires MockitoExtension or MockitoAnnotations.openMocks() to initialize.
Code Example
// Programmatic: Mockito.mock()
OrderRepository repo = Mockito.mock(OrderRepository.class);
// Declarative: the @Mock annotation (needs the MockitoExtension)
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock OrderRepository repo; // same kind of mock, less boilerplate
@InjectMocks OrderService service;
}
Common Mistakes & Pitfalls
- Using @Mock without @ExtendWith: Declaring fields with @Mock but forgetting @ExtendWith(MockitoExtension.class) on the test class—mocks remain null because nothing initializes them, causing NullPointerException on first use.
- Mixing both styles unnecessarily: Using @Mock at field level and then also calling Mockito.mock() in @BeforeEach for the same dependency, creating two separate mock instances and causing confusion.
- Calling MockitoAnnotations.openMocks() redundantly: Manually calling openMocks(this) in @BeforeEach when @ExtendWith already handles initialization—you initialize mocks twice, wasting resources and potentially causing subtle issues.
Check your understanding
Answer these without looking back at the article.
- What happens if you use @Mock without activating MockitoExtension?
- What is strict stubbing and why is it beneficial?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.