Skip to content
Advertisement

Why do MockMvc tests suggest injecting WebApplicationContext @BeforeEach test?

So the reference documentation suggests

    @BeforeEach
    void setup( WebApplicationContext wac) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup( wac )
            .apply( SecurityMockMvcConfigurers.springSecurity() )
            .alwaysDo( print() )
            .build();
    }

why not do it as constructor injection instead? (I haven’t tried this, I’m just assuming it doesn’t immediately blow up)

    @Autowired
    MyControllerTest(
        @NonNull WebApplicatonContext wac
    ) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup( wac )
            .apply( SecurityMockMvcConfigurers.springSecurity() )
            .alwaysDo( print() )
            .build();
    }

Advertisement

Answer

Whether you choose constructor injection, method injection, or field injection is a matter of taste when using JUnit Jupiter with the SpringExtension.

The example in the reference manual simply shows one way to do it using a @BeforeEach method since many people are familiar with performing test setup within a “before” method.

You can also set up your MockMvc instance within the test class constructor, and you can make your mockMvc field final if you like.

In this commit, I updated a test class in Spring’s own test suite to demonstrate some of these techniques in practice.

Please note that the test class constructor does not need to be annotated with @Autowired if it accepts a single argument that is compatible with ApplicationContext.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement