[英]How to return 400 status in model validation spring boot
我想測試我的StudentDTO
:
@Entity
@ToString
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class StudentDTO {
@Id
private int studentId;
@NotNull
@Size(min=2,max=30,message = "Name should consist of 2 to 30 symbols!")
private String studentName;
@NotNull
@Size(min = 2, max = 30,message = "Surname should consist of 2 to 30 symbols!")
private String studentSurname;
@NotNull
@Min(value = 10,message = "Student age should be more than 10!")
private int studentAge;
@NotNull
@Min(value = 1900,message = "Entry year should be more than 1900!")
@Max(value=2021,message = "Entry year should be less than 2021!")
private int entryYear;
@NotNull
@Min(value = 2020,message = "Graduate year should be not less than 2020!")
private int graduateYear;
@NotNull
@Size(min = 3,message = "Faculty name should consist of minimum 3 symbols!")
private String facultyName;
@NotNull
@Size(min = 4,message = "Group name should consist of 4 symbols!")
@Size(max = 4)
private String groupName;
}
在StudentController
進行測試的方法:
@PostMapping("successStudentAddition")
public String addStudent(@ModelAttribute("student") @Valid StudentDTO studentDTO, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute(STUDENT_MODEL, studentDTO);
return "/studentViews/addStudent";
}
Student student = new Student(studentDTO.getStudentId(), studentDTO.getStudentName(), studentDTO.getStudentSurname(),
studentDTO.getStudentAge(), studentDTO.getEntryYear(), studentDTO.getGraduateYear(), studentDTO.getFacultyName(),
groupService.getGroupIdByName(studentDTO.getGroupName()));
studentService.addStudent(student);
return "/studentViews/successStudentAddition";
}
我正在嘗試以這種方式進行測試:
@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = StudentController.class)
class StudentControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private StudentController studentController;
@Test
void whenInputIsInvalid_thenReturnsStatus400() throws Exception {
StudentDTO studentDTO = new StudentDTO();
studentDTO.setStudentId(0);
studentDTO.setStudentName("Sasha");
studentDTO.setStudentSurname("Georginia");
studentDTO.setStudentAge(0);
studentDTO.setEntryYear(5);
studentDTO.setGraduateYear(1);
studentDTO.setFacultyName("facop");
studentDTO.setGroupName("BIKS");
mvc.perform(post("/studentViews/successStudentAddition")
.accept(MediaType.TEXT_HTML))
.andExpect(status().isBadRequest())
.andExpect(model().attribute("student", studentDTO))
.andDo(print());
}
}
在我的測試中,我得到了 200 錯誤,但我需要得到 400 錯誤,並在我的StudentDTO
字段上確定上述錯誤。
例如,如果我通過studentAge = 5
,我應該得到 400 錯誤和消息: Student age should be more than 10!
就像在StudentDTO
。
我經常求助於 spring 的org.springframework.http.ResponseEntity 類。
@PostMapping("successStudentAddition")
public ResponseEntity<String> addStudent(@ModelAttribute("student") @Valid StudentDTO studentDTO, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute(STUDENT_MODEL, studentDTO);
return new ResponseEntity<String>("/studentViews/addStudent", HttpStatus.BAD_REQUEST);
}
Student student = new Student(studentDTO.getStudentId(), studentDTO.getStudentName(), studentDTO.getStudentSurname(),
studentDTO.getStudentAge(), studentDTO.getEntryYear(), studentDTO.getGraduateYear(), studentDTO.getFacultyName(),
groupService.getGroupIdByName(studentDTO.getGroupName()));
studentService.addStudent(student);
return new ResponseEntity<String>("/studentViews/successStudentAddition", HttpStatus.Ok);
}
當您遇到這樣的情況時,Spring 將拋出MethodArgumentNotValidException
。 要處理這些異常,您可以使用@ControllerAdvice
編寫一個類。
@ControllerAdvice
public class ErrorHandler {
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
public ResponseEntity<Error> invalidArgumentExceptionHandler(MethodArgumentNotValidException ex) {
// Instead of "/studentViews/successStudentAddition" you can return to some generic error page.
return new ResponseEntity<String>("/studentViews/successStudentAddition", HttpStatus.BAD_REQUEST);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.