Spring Boot unit test constructor injection

It’s fine for your test to use field injection as the Test itself is not part of your domain; the test won’t be part of your application context.


You don’t want to use SpringBootTest to test a controller, because that will wire ALL beans which can be way too heavy and time-consuming. Instead, you probably only want to create your controller and it’s dependencies.

So your best option is to use @WebMvcTest which will only create the beans required for testing the specified controller.

@WebMvcTest(controllers = PersonController.class)
class PersonControllerTest {
    private MockMvc mockMvc;

    public void greetingShouldReturnDefaultMessage() throws Exception {

Note that @WebMvcTest will search for a class annotated with @SpringBootConfiguration as it’s default configuration. If it does not find it, or you want to manually specify some configuration classes, also annotate the test with @ContextConfiguration.

Also, as a sidenote, when using TestRestTemplate, you don’t need to specify host and port. Just call restTemplate.getForObject("/cvtech/persons", String.class)); Same when using MockMvc or WebTestClient.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top