如何在模型验证中返回400状态 Spring Boot

huangapple go评论87阅读模式
英文:

How to return 400 status in model validation spring boot

问题

我想测试我的StudentDTO

  1. @Entity
  2. @ToString
  3. @Setter
  4. @Getter
  5. @NoArgsConstructor
  6. @AllArgsConstructor
  7. public class StudentDTO {
  8. @Id
  9. private int studentId;
  10. @NotNull
  11. @Size(min=2,max=30,message = "Name should consist of 2 to 30 symbols!")
  12. private String studentName;
  13. @NotNull
  14. @Size(min = 2, max = 30,message = "Surname should consist of 2 to 30 symbols!")
  15. private String studentSurname;
  16. @NotNull
  17. @Min(value = 10,message = "Student age should be more than 10!")
  18. private int studentAge;
  19. @NotNull
  20. @Min(value = 1900,message = "Entry year should be more than 1900!")
  21. @Max(value=2021,message = "Entry year should be less than 2021!")
  22. private int entryYear;
  23. @NotNull
  24. @Min(value = 2020,message = "Graduate year should be not less than 2020!")
  25. private int graduateYear;
  26. @NotNull
  27. @Size(min = 3,message = "Faculty name should consist of minimum 3 symbols!")
  28. private String facultyName;
  29. @NotNull
  30. @Size(min = 4,message = "Group name should consist of 4 symbols!")
  31. @Size(max = 4)
  32. private String groupName;
  33. }

用于在StudentController中进行测试的方法:

  1. @PostMapping("successStudentAddition")
  2. public String addStudent(@ModelAttribute("student") @Valid StudentDTO studentDTO, Errors errors, Model model) {
  3. if (errors.hasErrors()) {
  4. model.addAttribute(STUDENT_MODEL, studentDTO);
  5. return "/studentViews/addStudent";
  6. }
  7. Student student = new Student(studentDTO.getStudentId(), studentDTO.getStudentName(), studentDTO.getStudentSurname(),
  8. studentDTO.getStudentAge(), studentDTO.getEntryYear(), studentDTO.getGraduateYear(), studentDTO.getFacultyName(),
  9. groupService.getGroupIdByName(studentDTO.getGroupName()));
  10. studentService.addStudent(student);
  11. return "/studentViews/successStudentAddition";
  12. }

我尝试以以下方式进行测试:

  1. @ExtendWith(SpringExtension.class)
  2. @WebMvcTest(controllers = StudentController.class)
  3. class StudentControllerTest {
  4. @Autowired
  5. private MockMvc mvc;
  6. @Autowired
  7. private ObjectMapper objectMapper;
  8. @MockBean
  9. private StudentController studentController;
  10. @Test
  11. void whenInputIsInvalid_thenReturnsStatus400() throws Exception {
  12. StudentDTO studentDTO = new StudentDTO();
  13. studentDTO.setStudentId(0);
  14. studentDTO.setStudentName("Sasha");
  15. studentDTO.setStudentSurname("Georginia");
  16. studentDTO.setStudentAge(0);
  17. studentDTO.setEntryYear(5);
  18. studentDTO.setGraduateYear(1);
  19. studentDTO.setFacultyName("facop");
  20. studentDTO.setGroupName("BIKS");
  21. mvc.perform(post("/studentViews/successStudentAddition")
  22. .accept(MediaType.TEXT_HTML))
  23. .andExpect(status().isBadRequest())
  24. .andExpect(model().attribute("student", studentDTO))
  25. .andDo(print());
  26. }
  27. }

在我的测试中,我得到了200错误,但我需要根据StudentDTO中的字段获得400错误以及上面指定的错误消息。

例如,如果我传递studentAge = 5,我应该获得400错误和消息:Student age should be more than 10!,就像在StudentDTO中一样。

英文:

I want to test my StudentDTO :

  1. @Entity
  2. @ToString
  3. @Setter
  4. @Getter
  5. @NoArgsConstructor
  6. @AllArgsConstructor
  7. public class StudentDTO {
  8. @Id
  9. private int studentId;
  10. @NotNull
  11. @Size(min=2,max=30,message = "Name should consist of 2 to 30 symbols!")
  12. private String studentName;
  13. @NotNull
  14. @Size(min = 2, max = 30,message = "Surname should consist of 2 to 30 symbols!")
  15. private String studentSurname;
  16. @NotNull
  17. @Min(value = 10,message = "Student age should be more than 10!")
  18. private int studentAge;
  19. @NotNull
  20. @Min(value = 1900,message = "Entry year should be more than 1900!")
  21. @Max(value=2021,message = "Entry year should be less than 2021!")
  22. private int entryYear;
  23. @NotNull
  24. @Min(value = 2020,message = "Graduate year should be not less than 2020!")
  25. private int graduateYear;
  26. @NotNull
  27. @Size(min = 3,message = "Faculty name should consist of minimum 3 symbols!")
  28. private String facultyName;
  29. @NotNull
  30. @Size(min = 4,message = "Group name should consist of 4 symbols!")
  31. @Size(max = 4)
  32. private String groupName;
  33. }

Method for testing in StudentController :

  1. @PostMapping("successStudentAddition")
  2. public String addStudent(@ModelAttribute("student") @Valid StudentDTO studentDTO, Errors errors, Model model) {
  3. if (errors.hasErrors()) {
  4. model.addAttribute(STUDENT_MODEL, studentDTO);
  5. return "/studentViews/addStudent";
  6. }
  7. Student student = new Student(studentDTO.getStudentId(), studentDTO.getStudentName(), studentDTO.getStudentSurname(),
  8. studentDTO.getStudentAge(), studentDTO.getEntryYear(), studentDTO.getGraduateYear(), studentDTO.getFacultyName(),
  9. groupService.getGroupIdByName(studentDTO.getGroupName()));
  10. studentService.addStudent(student);
  11. return "/studentViews/successStudentAddition";
  12. }

I am trying to test in this way :

  1. @ExtendWith(SpringExtension.class)
  2. @WebMvcTest(controllers = StudentController.class)
  3. class StudentControllerTest {
  4. @Autowired
  5. private MockMvc mvc;
  6. @Autowired
  7. private ObjectMapper objectMapper;
  8. @MockBean
  9. private StudentController studentController;
  10. @Test
  11. void whenInputIsInvalid_thenReturnsStatus400() throws Exception {
  12. StudentDTO studentDTO = new StudentDTO();
  13. studentDTO.setStudentId(0);
  14. studentDTO.setStudentName("Sasha");
  15. studentDTO.setStudentSurname("Georginia");
  16. studentDTO.setStudentAge(0);
  17. studentDTO.setEntryYear(5);
  18. studentDTO.setGraduateYear(1);
  19. studentDTO.setFacultyName("facop");
  20. studentDTO.setGroupName("BIKS");
  21. mvc.perform(post("/studentViews/successStudentAddition")
  22. .accept(MediaType.TEXT_HTML))
  23. .andExpect(status().isBadRequest())
  24. .andExpect(model().attribute("student", studentDTO))
  25. .andDo(print());
  26. }
  27. }

In my test I got 200 error, but I need to get 400 error with determined error above on the field from my StudentDTO.

e.g. if I pass studentAge = 5, I should to get 400 error and the message : Student age should be more than 10! like in the StudentDTO.

答案1

得分: 1

以下是您要翻译的内容:

当您遇到这样的情况时,Spring 将会抛出 MethodArgumentNotValidException。要处理这些异常,您可以编写一个带有 @ControllerAdvice 注解的类。

  1. @ControllerAdvice
  2. public class ErrorHandler {
  3. @ExceptionHandler(value = {MethodArgumentNotValidException.class})
  4. public ResponseEntity<Error> invalidArgumentExceptionHandler(MethodArgumentNotValidException ex) {
  5. // 而不是返回 "/studentViews/successStudentAddition",您可以返回一些通用的错误页面。
  6. return new ResponseEntity<String>("/studentViews/successStudentAddition", HttpStatus.BAD_REQUEST);
  7. }
  8. }
英文:

When you have such a condition, Spring will throw MethodArgumentNotValidException. To handle these exceptions you can write a class with @ControllerAdvice.

  1. @ControllerAdvice
  2. public class ErrorHandler {
  3. @ExceptionHandler(value = {MethodArgumentNotValidException.class})
  4. public ResponseEntity&lt;Error&gt; invalidArgumentExceptionHandler(MethodArgumentNotValidException ex) {
  5. // Instead of &quot;/studentViews/successStudentAddition&quot; you can return to some generic error page.
  6. return new ResponseEntity&lt;String&gt;(&quot;/studentViews/successStudentAddition&quot;, HttpStatus.BAD_REQUEST);
  7. }
  8. }

答案2

得分: 0

I often turn to spring's org.springframework.http.ResponseEntity class.

  1. @PostMapping("successStudentAddition")
  2. public ResponseEntity<String> addStudent(@ModelAttribute("student") @Valid StudentDTO studentDTO, Errors errors, Model model) {
  3. if (errors.hasErrors()) {
  4. model.addAttribute(STUDENT_MODEL, studentDTO);
  5. return new ResponseEntity<String>("/studentViews/addStudent", HttpStatus.BAD_REQUEST);
  6. }
  7. Student student = new Student(studentDTO.getStudentId(), studentDTO.getStudentName(), studentDTO.getStudentSurname(),
  8. studentDTO.getStudentAge(), studentDTO.getEntryYear(), studentDTO.getGraduateYear(), studentDTO.getFacultyName(),
  9. groupService.getGroupIdByName(studentDTO.getGroupName()));
  10. studentService.addStudent(student);
  11. return new ResponseEntity<String>("/studentViews/successStudentAddition", HttpStatus.Ok);
  12. }
英文:

I often turn to spring's org.springframework.http.ResponseEntity class.

  1. @PostMapping(&quot;successStudentAddition&quot;)
  2. public ResponseEntity&lt;String&gt; addStudent(@ModelAttribute(&quot;student&quot;) @Valid StudentDTO studentDTO, Errors errors, Model model) {
  3. if (errors.hasErrors()) {
  4. model.addAttribute(STUDENT_MODEL, studentDTO);
  5. return new ResponseEntity&lt;String&gt;(&quot;/studentViews/addStudent&quot;, HttpStatus.BAD_REQUEST);
  6. }
  7. Student student = new Student(studentDTO.getStudentId(), studentDTO.getStudentName(), studentDTO.getStudentSurname(),
  8. studentDTO.getStudentAge(), studentDTO.getEntryYear(), studentDTO.getGraduateYear(), studentDTO.getFacultyName(),
  9. groupService.getGroupIdByName(studentDTO.getGroupName()));
  10. studentService.addStudent(student);
  11. return new ResponseEntity&lt;String&gt;(&quot;/studentViews/successStudentAddition&quot;, HttpStatus.Ok);
  12. }

huangapple
  • 本文由 发表于 2020年10月16日 02:33:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64377726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定