I have a Spring Boot 2.5.3 project and I am attempting to validate some models. However, the tests are returning a 200
status when I am expecting a 4xx
error.
Sample endpoint under test:
@PostMapping("/reports")
public CAReportDTO addReport(@Valid @RequestBody CAReportDTO caReport) {
return this.caService.submitForm(caReport);
}
where CAReportDTO has the following annotations (in part):
public class CAReportDTO {
private int id;
@Size(min = 5, max = 7, message
= "Employee ID must be between 5 and 7 characters long.")
@NotNull
private String empId;
private int formId;
private String formTitle;
@Size(min = 4, max = 5, message
= "Work location must be between 4 and 5 characters long.")
@NotNull
private String workLocId;
private CAStatus statusId;
@NotNull
@PastOrPresent
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate incidentDate;
The controller test is as follows (it should fail on both the empId and incidentDate fields):
@Test
@WithMockUser(username = "admin", authorities = { RoleConstants.HR.WRK_MNG_CAS })
public void testAddInvalidReport() throws Exception {
var dto = new CAReportDTO("test", TEST_ID, "w", LocalDate.now(), "t");
var jString = mapper.writeValueAsString(dto);
given(this.caService.submitForm(any(CAReportDTO.class))).willReturn(dto);
this.mvc.perform(post("/cas/reports").contentType(MediaType.APPLICATION_JSON).content(jString))
.andExpect(status().is2xxSuccessful());
dto.setIncidentDate(LocalDate.now().plusMonths(2));
dto.setEmpId("111111111111111111111111111");
jString = mapper.writeValueAsString(dto);
this.mvc.perform(post("/cas/reports").contentType(MediaType.APPLICATION_JSON).content(jString))
.andExpect(status().is4xxClientError());
}
The test is failing because the last call returns 200
instead of the expected client error.
I did include org.springframework.boot:spring-boot-starter-validation
in my dependencies.
The DTO is actually in a separate library (which is using group: 'org.hibernate.validator:hibernate-validator:7.0.1.Final'
for the annotations). Not sure if any version conflicts would cause this?
Thanks!
EDIT: Setup for test class:
@WebMvcTest(CAController.class)
@ActiveProfiles("test")
public class CAControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private CAService caService;
@Autowired
private ObjectMapper mapper;
// @Test methods
}