Mixing Unit and Spring Annotations
Fast recall
Quick revision
Core answer
Whether the candidate has clear conceptual boundaries between test types and doesn't blur the lines.
Adding @SpringBootTest to tests that only test a service method, treating all tests as integration tests.
Explain that @ExtendWith(MockitoExtension.class) is the correct choice for unit tests and doesn't involve Spring at all—it's pure JUnit 5 and Mockito.
Interview-ready guide
Interview answer
A unit test can use JUnit, Mockito, or even a small Spring utility; the category is determined by the boundary it exercises. If the test loads an ApplicationContext to verify real bean wiring, transactions, MVC mapping, or persistence behavior, it is integration-style. If it constructs one subject directly and controls its collaborators, it remains a unit test even when those classes use Spring annotations in production. MockitoExtension is a convenient way to initialize local mocks, but it is not required. The practical rule is to start Spring only when Spring-managed behavior is part of the requirement.
Mixing Unit and Spring Annotations
Direct Answer
A unit test can use annotations, including JUnit or Mockito annotations, without becoming an integration test. What matters is the boundary it exercises. Loading a Spring ApplicationContext to test real Spring wiring makes it an integration-style test; merely using a small Spring utility or annotation does not automatically do so. Prefer plain construction when framework behavior is not under test.
Code Example
@ExtendWith(MockitoExtension.class)
class PaymentServiceTest {
@Mock // Mockito's mock, not Spring's
private PaymentGateway paymentGateway;
@Mock
private OrderRepository orderRepository;
@InjectMocks // Mockito injects mocks, not Spring
private PaymentService paymentService;
@Test
void shouldProcessPaymentSuccessfully() {
var order = new Order(1L, "Laptop", 1500.0);
when(paymentGateway.charge(1500.0)).thenReturn(true);
var result = paymentService.processPayment(order); // pure logic test
assertTrue(result);
verify(paymentGateway).charge(1500.0); // no Spring context involved
}
}
Common Mistakes & Pitfalls
- Classifying by annotation name: The actual boundary and behavior under test matter more than whether a helper annotation comes from Spring.
- Loading @SpringBootTest for local logic: If wiring is not under test, direct construction gives a clearer, smaller test.
- Confusing mock scopes: @Mock creates a local Mockito mock. @MockitoBean, or @MockBean on older Boot, supplies or replaces a bean in a Spring test context.
Check your understanding
Answer these without looking back at the article.
- What is SpringExtension and how does it relate to @SpringBootTest?
- Is @RunWith(SpringRunner.class) still used in Spring Boot 3?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.