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

Viewed 3754

I'm testing a Spring MVC @RestController which in turn makes a call to an external REST service. I use MockMvc to simulate the spring environment but I expect my controller to make a real call to the external service. Testing the RestController manually works fine (with Postman etc.).

I found that if I setup the test in a particular way I get a completely empty response (except 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 fails because the content and headers are empty. Then I tried adding this to the test class:

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

and additionally I changed the ContextConfiguration annotation (although I'd like to know what this actually does):

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

Now suddenly all the checks succeed and when printing the content body I'm getting all the content.

What is happening here? What is the difference between these two approaches?

1 Answers
Related