I have a weird issue with a unit test and ResponseEntity. Here's the test:
@Test
@DirtiesContext
public void createEntityTest() {
EntityRequestDTO requestDTO = new EntityRequestDTO();
dto.setTitle("foo");
dto.setDescription("bar");
ResponseEntity<EntityResponseDTO> postResponse =
testRestTemplate.postForEntity("/api/test", dto, EntityResponseDTO.class);
EntityResponseDTO responseDTO = postResponse.getBody();
assertThat(responseDTO.getTitle()).isEqualTo("foo");
assertThat(responseDTO.getDescription()).isEqualTo("bar");
assertThat(responseDTO.getFullname()).isEqualTo("foobar");
}
The full name is set in the background by service. The issue is, this last assertion fails. getFullname() returns null. That may be because of several reasons, but, here's the controller endpoint:
@PostMapping("/api/test")
public ResponseEntity<EntityResponseDTO> create(@RequestBody EntityRequestDTO requestDTO) {
Entity saved = entityService.add(requestDTO);
EntityResponseDTO savedDto = new EntityResponseDTO(saved);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.getId())
.toUri();
ResponseEntity<EntityResponseDTO> resEntity = ResponseEntity.created(location).body(savedDto);
System.out.println("Before: ResponseEntity in controller.");
System.out.println(resEntity.getBody().getFullname());
}
However here, just before returning the ResponseEntity the System.out.println(resEntity.getBody().getFullname()) method prints foobar. I can't wrap my head around this. What is going on?
Note: I have @JsonIgnore on the fullname field because I want it to be present, but not shown in the response. When removing annotation, test passes.