Spring Boot integration tests: @AutoConfigureMockMvc and context caching

Vitaljok picture Vitaljok · Mar 9, 2017 · Viewed 7.3k times · Source

I'm building very basic web application using Spring Boot 1.5.1 and wanted to create integration tests for checking REST endpoints. As recomended by documentation, MockMvc might be used for it.

Here is very simple test class:

package foo.bar.first;

import ...

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationTest1 {

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private MockMvc mvc;

    @Test
    public void shouldStartWebApplicationContext() {
        assertThat(context).isNotNull();
    }

    @Test
    public void shouldReplyToPing() throws Exception {
        mvc.perform(get("/ping"))
                .andExpect(status().isOk());
    }
}

As expected, it starts full application context and runs tests.

Later I have created other similar test classes and noticed that brand new application context is started up for each test class. Experiments show that context is shared only between test classes from same package.

For example, if same test class copied multiple times, then contexts are as follows:

foo.bar
  first
    ApplicationTest1 (shared context)
    ApplicationTest2 (shared context)
  second
    ApplicationTest3 (brand new context)

Also further investigations showed that it is related to @AutoConfigureMockMvc annotation. If the annotation and MockMvc related test cases are removed, then all three classes sucessfully share the same context.

So the question is how to get shared context for all tests with MockMvc?

Note: other resources suggest to use MockMvcBuilders.webAppContextSetup(context).build() for getting MockMvc instance, but it does not work for me (it does not involve filters when processing web requests).

Answer

Harald Brabenetz picture Harald Brabenetz · Jun 9, 2017

It seems to be a Bug introduced with Spring Boot 1.5: https://github.com/spring-projects/spring-boot/issues/9282

You can try a downgrade to Spring Boot 1.4.x or wait for the fixed version (planed for the next release 1.5.5).

Update: Instead of "@AutoConfigureMockMvc" you can also manual configure your MockMVC: https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/test-mockmvc.html

Manual configure the MockMVC worked fine on my project.
What do you mean with "it does not involve filters when processing web requests"?