Spring 5.0.0 MockMvc:不支持的媒体类型,即使MediaType设置正确

时间:2017-10-09 19:41:38

标签: java spring spring-mvc mockmvc spring-test-mvc

我正在使用JUnit4和Spring Web MVC Test,我有一个Controller的测试类。

Controller处理对" / test"的POST请求。与JSON正文内容。我已经使用Postman手动测试了这个方法,我得到了400 Bad Request响应,正如预期的那样,因为" name"财产是空的。

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

{
    "name": ""
}

但是,当我通过我的测试类向Controller发送相同的请求时,即使请求相同,我也会收到415(不支持的媒体类型)错误。

@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());
    }
}

这是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) {
    }
}

这是MyDTO。

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

我的依赖也有杰克逊。

以下是测试类的请求在打印到控制台时的样子:&/ p>

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 = []

无论如何,为什么我会收到这个错误?请求对我来说非常好。任何帮助表示赞赏。感谢。

1 个答案:

答案 0 :(得分:4)

我通过使用@EnableWebMvc注释我的MyControllerTestConfiguration内部静态类来解决这个问题。

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

    @Configuration
    @EnableWebMvc // <------------ added this
    public static class MyControllerTestConfiguration {

        @Bean
        public SetupController setupController() {
            return new MyController();
        }

    }