13
votes

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).

1
I have exactly the same problem. The only workaround I have found is to not use mockMvc and use TestRestTemplate, which is definitely not a good solution. - Andrea Bergia
Have you tried setting up mockmvc in a base class and the extending that class for each test suite? And I'm also curious why you need the tests to share context?` I like this setup covered in the spring.io blog. testing each controller induvidually. - Pär Nilsson
"And I'm also curious why you need the tests to share context?" @PärNilsson, as I mentioned in question, I'm running integration tests, and my idea was to run whole web tier together with underlying services to test how they work together. - Vitaljok

1 Answers

3
votes

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"?