问题测试在Spring MockMvc中接受请求标头

时间:2017-12-08 12:05:21

标签: spring-mvc spring-boot junit mocking

我正在尝试对SpringBoot Controller进行单元测试。目标是测试我们在请求标头包含406 Not AcceptableAccept返回application/json以外的任何内容。但我发现它不适用于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();
    }

}

2 个答案:

答案 0 :(得分:0)

啊!我已经确定并修复了这个问题。在控制器中我们需要@RequestMapping(headers="Accept=application/json")。其他MockMvc无法确定预期的格式。

答案 1 :(得分:0)

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

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