【发布时间】: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