Technically it should be a simple task, but I can’t find the error.
I want to write a normal “POST method”, but when I tested it, it came to a problem: enter code here Status expected:<201> but what:<200>.
My question is, why do I get an OK and not a CREATED?
CODE:
PostMapping in Controller
@PostMapping public Optional<ADto> createA(@RequestBody ADto a){ return Optional.ofNullable(a); }
Unit Test
@Test void verifyPostA() throws Exception { var a = new ADto(1L, "a"); var aText = objectMapper.writeValueAsString(a); mockMvc.perform( MockMvcRequestBuilders.post("/as") .content(aText) .contentType(MediaType.APPLICATION_JSON) ) .andDo(print()) .andExpect(status().isCreated()) .andExpect(jsonPath("$.id").value("1")); }
Advertisement
Answer
Because for a controller method that executes successfully and does not return ResponseEntity
, the default response code is 200.
To configure the response code for such case , you can simply annotate @ResponseStatus
on that controller method :
@PostMapping @ResponseStatus(HttpStatus.CREATED) public Optional<ADto> createA(@RequestBody ADto a){ return Optional.ofNullable(a); }