[英]How to return 400 status in model validation spring boot
I want to test my StudentDTO
:我想测试我的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;
}
Method for testing in StudentController
:在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";
}
I am trying to test in this way :我正在尝试以这种方式进行测试:
@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());
}
}
In my test I got 200 error, but I need to get 400 error with determined error above on the field from my StudentDTO
.在我的测试中,我得到了 200 错误,但我需要得到 400 错误,并在我的StudentDTO
字段上确定上述错误。
eg if I pass studentAge = 5
, I should to get 400 error and the message : Student age should be more than 10!
例如,如果我通过studentAge = 5
,我应该得到 400 错误和消息: Student age should be more than 10!
like in the StudentDTO
.就像在StudentDTO
。
I often turn to spring's org.springframework.http.ResponseEntity class .我经常求助于 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);
}
When you have such a condition, Spring will throw MethodArgumentNotValidException
.当您遇到这样的情况时,Spring 将抛出MethodArgumentNotValidException
。 To handle these exceptions you can write a class with @ControllerAdvice
.要处理这些异常,您可以使用@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.