Springs MockMvc returns empty content in one of two only slightly different approaches

I am testing Spring MVC @RestController

which in turn makes a call to an external REST service. I'm using MockMvc

Spring for modeling, but I'm expecting my controller to make a real call to an external service. Testing the RestController by hand works fine (with Postman, etc.).

I found that if I set up the test in a certain way, I get a completely empty response (other than the status code):

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = AnywhereController.class)
public class AnywhereControllerTest{

    @Autowired
    private AnywhereController ac;

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testGetLocations() throws Exception {

        ...

        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/anywhere/locations").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("locations")))
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
        .andReturn();
    } 

      

The test failed because the content and headers are empty. Then I tried to add this to the test class:

@Configuration
@EnableWebMvc
public static class TestConfiguration{
    @Bean
    public AnywhereController anywhereController(){
        return new AnywhereController();
    }
}

      

and in addition, I changed the annotation ContextConfiguration

(although I would like to know what it actually does):

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class AnywhereControllerTest{...}

      

Now all of a sudden, all validations succeed and when I print the body content, I get all the content.

What's going on here? What is the difference between these two approaches?

+3


source to share


1 answer


Someone in the comments mentioned @EnableWebMvc and it turned out to be the right lead. I have not used @EnableWebMvc and therefore

If you don't use this annotation, you may not initially notice any difference, but things like content-type and accepting a title generally won't work content negotiation. Source



My knowledge of the inner workings of the framework is limited, but this simple warning during startup can potentially save many hours of debugging. Most likely when people use @Configuration and / or @RestController they also want to use @EnableWebMvc (or xml version).

To make matters worse, Spring Boot, for example, adds this annotation automatically, which is why many tutorials on the Internet (also official) don't mention @EnableWebMvc.

+2


source







All Articles