javaspringspring-mvcmockmvcspring-test-mvc

Spring 5.0.0 MockMvc: Unsupported media type, even with correct MediaType set


I am using JUnit4 with Spring Web MVC Test and I have test class for a Controller.

The Controller handles a POST request to "/test" with JSON body content. I've tested this method manually using Postman and I get a 400 Bad Request response, as expected, since the "name" property is empty.

POST /Server/test HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache

{
    "name": ""
}

However, when I send the same request to my Controller through my test class, I get a 415 (Unsupported Media Type) error, even though the request is the same.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class MyControllerTest {

@Configuration
public static class MyControllerTestConfiguration {

    @Bean
    public MyController myController() {
        return new MyController();
    }
}

private MockMvc mockMvc;

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

@Test
public void shouldReturnBadRequest_IfBodyIsEmpty() throws Exception {
    // Works fine
    mockMvc.perform(post("/test"))
           .andExpect(status().isBadRequest());
}

@Test
public void shouldReturnBadRequest_IfInvalidFields() throws Exception {

    MyDTO dto = new MyDTO();
    dto.setName("");

    // Jackson object mapper
    ObjectMapper mapper = new ObjectMapper();

    // TEST FAIL: Gets 415 error
    mockMvc.perform(
                post("/test")
                .content(mapper.writeValueAsString(dto))
                .characterEncoding("UTF-8")
                .contentType(MediaType.APPLICATION_JSON)
            )
            .andDo(print())
            .andExpect(status().isBadRequest());
    }
}

And here's MyController.

@RestController
@EnableWebMvc
public class MyController {

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public void init(@javax.validation.Valid @RequestBody MyDTO dto) {
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public void validationError(MethodArgumentNotValidException ex) {
    }
}

And here's MyDTO.

@lombok.Data
public class MyDTO {
    private String name;
}

I have Jackson in my dependencies as well.

Here's what the test class's request looks like when it's printed to the console:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /test
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8]}
             Body = {"name":""}
    Session Attrs = {}

Handler:
             Type = controller.MyController
           Method = public void controller.MyController.init(dto.MyDTO)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotSupportedException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 415
    Error message = null
          Headers = {Accept=[application/octet-stream, text/plain, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, */*]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Anyways, why would I be getting this error? The request looks perfectly fine to me. Any help is appreciated. Thanks.


Solution

  • I've solved the issue by annotating my MyControllerTestConfiguration inner static class with @EnableWebMvc.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    @WebAppConfiguration
    public class MyControllerTest {
    
        @Configuration
        @EnableWebMvc // <------------ added this
        public static class MyControllerTestConfiguration {
    
            @Bean
            public SetupController setupController() {
                return new MyController();
            }
    
        }