@Autowired marks a dependency for injection from the Spring application context. In Spring Boot tests, it gives test code direct access to application beans, collections of beans, or selected beans qualified by name. section 1.4 section 3.2
Use @Autowired in tests to:
- Inject repositories or services for preparing state and verifying application behavior. section 2.4
- Inject a collection such as List<Thing> to inspect all matching beans in the context. section 3.2
- Combine @Autowired with @Qualifier to select a bean by name, such as redThing. section 3.2
- Replace a production dependency with a test-specific mock by pairing context-based testing with @MockitoBean. section 1.4
Injecting dependencies into a Spring Boot test
A test can inject MockMvc and a repository, exercise an HTTP endpoint, and verify the resulting state. Method-parameter injection also supports selecting a particular bean with @Qualifier. Prefer services or controllers when verifying behavior rather than coupling tests directly to repository data models. section 2.4
Listing 3.3 Accessing the Spring context
@SpringBootTest
class InteractWithAppTests {
@Autowired #1
List<Thing> things;
@Value("${demo.value}") #2
int value;
@Test
void things() {
var names = things.stream().map(Thing::name);
assertThat(names).contains("red", "pink", "green", "orange");
}
@Test
void value() {
assertThat(value).isEqualTo(1);
}
@Test
void redThing(@Qualifier("redThing") @Autowired Thing redThing) { #3
assertThat(redThing.name()).isEqualTo("red");
}
}
Inspect field injection, collection injection, configuration-property access, and qualified method-parameter injection in one compact test. section 3.2


