Reputation: 451
I am trying to unit test SpringBoot Controller. Objective is to test that we return 406 Not Acceptable
when request header contains Accept
as anything other than application/json
. But I find its not working with MockMvc
. I am getting 200 OK instead of 406. Any ideas please! Of course, service returns 406 as expected when I test using Postman or any rest client.
@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();
}
And my controller looks like,
@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();
}
}
Upvotes: 4
Views: 8513
Reputation: 948
You might consider using the accept() method instead, e.g.
mvc.perform( MockMvcRequestBuilders
.get("/some/test/url")
.content(...)
.accept(MediaType.APPLICATION_XML)
.andExpect(...)
Upvotes: 1
Reputation: 451
Ahh! I have identified and fixed the issue. In the controller we need to have, @RequestMapping(headers="Accept=application/json")
. Else MockMvc is not able to identify the expected format.
Upvotes: 0