@Autowired in @SpringBootTest
Fast recall
Quick revision
Core answer
Basic Spring dependency injection knowledge applied to the test context, confirming they understand DI works the same way in tests
Thinking @Autowired doesn't work in tests or manually calling applicationContext.getBean() instead of using field injection
Explain that the TestContext framework prepares the test instance and can inject context beans; for context-level Mockito overrides, use current @MockitoBean or older Boot @MockBean
Interview-ready guide
Interview answer
Yes. Spring's TestContext framework can inject beans from the test ApplicationContext into the test instance. Field and setter injection are straightforward, and constructor injection is supported under the test-constructor rules. The requested bean must actually exist in that context. The test class is prepared by the testing framework rather than becoming an ordinary application bean. If one dependency must be replaced by a Mockito mock in the context, use current @MockitoBean or @MockBean on older Spring Boot versions. A plain @Mock is enough only when the test constructs the subject itself and does not need Spring.
@Autowired in @SpringBootTest
Direct Answer
Yes. The Spring TestContext framework can inject beans from the test ApplicationContext into fields, setters, or constructors of the test instance. The test instance is managed by the testing framework with Spring support; it is not an ordinary application bean, and only beans present in that test context can be injected.
Code Example
@SpringBootTest
class OrderServiceIntegrationTest {
@Autowired
private OrderService orderService;
@Autowired
private OrderRepository orderRepository;
@MockitoBean
private PaymentClient paymentClient; // use @MockBean on older Boot
@Test
void shouldCreateOrderWithMockedPayment() {
when(paymentClient.charge(anyDouble())).thenReturn(true);
var order = orderService.createOrder("laptop", 999.99);
assertThat(order.getId()).isNotNull();
verify(paymentClient).charge(999.99);
}
}
Common Mistakes & Pitfalls
- Assuming any class can be injected: @Autowired can only resolve a bean available in the test context.
- Treating the test as an application bean: TestContext prepares the test instance, but it does not make the class an ordinary application component.
- Confusing @Mock with a bean override: Use @MockitoBean in current Spring, or @MockBean on older Boot, when the mock must replace or provide a bean in the context.
Check your understanding
Answer these without looking back at the article.
- What happens to the @MockBean between test methods — is it reset?
- Can you use constructor injection in a @SpringBootTest test class?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.