【问题标题】:Issue testing Accept request header in Spring MockMvc在 Spring MockMvc 中发布测试 Accept 请求标头
【发布时间】:2018-05-22 16:23:00
【问题描述】:

我正在尝试对 SpringBoot 控制器进行单元测试。目标是测试当请求标头包含Accept 而不是application/json 时我们返回406 Not Acceptable。但我发现它不适用于MockMvc。我得到 200 OK 而不是 406。请有任何想法!当然,当我使用 Postman 或任何其他客户端进行测试时,服务会按预期返回 406。

@Test
public void shouldRejectIfInvalidAcceptHeaderIsPassed() throws Exception {

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Accept","application/xml");
    httpHeaders.add("Authorization", "some jwt token");

    this.mockMvc.perform(post("/sample/test")
            .contentType(MediaType.APPLICATION_JSON)
            .headers(httpHeaders)
            .content(toJson("")))
            .andExpect(status().isNotAcceptable());

    // Then
    verify(mockSampleService).getSampleOutput();
}

我的控制器看起来像,

@RestController
@Validated
@RequestMapping(PATH_PREFIX)
public class SampleController {

    public static final String PATH_PREFIX = “/sample”;

    private final SampleService sampleService;

    @Autowired
    public SampleController(SampleService sampleService) {
        sampleService = sampleService;
    }


    @RequestMapping(value = “/test”, method = RequestMethod.POST))
    public SampleResponse createSession() {
        return sampleService.getSampleOutput();
    }

}

【问题讨论】:

    标签: spring-mvc spring-boot junit mocking


    【解决方案1】:

    您可以考虑改用 accept() 方法,例如

        mvc.perform( MockMvcRequestBuilders
            .get("/some/test/url")
            .content(...)
            .accept(MediaType.APPLICATION_XML)
            .andExpect(...)
    

    【讨论】:

      【解决方案2】:

      啊!我已经确定并解决了这个问题。在我们需要的控制器中,@RequestMapping(headers="Accept=application/json")。否则 MockMvc 无法识别预期的格式。

      【讨论】:

      • 你可以添加:@RequestMapping(PATH_PREFIX,produces = "application/json", consumes = "application/json")
      猜你喜欢
      • 1970-01-01
      • 2014-11-10
      • 2017-10-28
      • 2013-10-14
      • 1970-01-01
      • 2013-08-13
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多