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

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

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错误,但我需要根据StudentDTO中的字段获得400错误以及上面指定的错误消息。

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

英文:

I want to test my 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 :

@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.

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 注解的类。

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

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

@ControllerAdvice
public class ErrorHandler {
     

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseEntity&lt;Error&gt; invalidArgumentExceptionHandler(MethodArgumentNotValidException ex) {
// Instead of &quot;/studentViews/successStudentAddition&quot; you can return to some generic error page.
            return new ResponseEntity&lt;String&gt;(&quot;/studentViews/successStudentAddition&quot;, HttpStatus.BAD_REQUEST);
    }
}

答案2

得分: 0

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

@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);
}
英文:

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

@PostMapping(&quot;successStudentAddition&quot;)
public ResponseEntity&lt;String&gt; addStudent(@ModelAttribute(&quot;student&quot;) @Valid StudentDTO studentDTO, Errors errors, Model model) {

    if (errors.hasErrors()) {
        model.addAttribute(STUDENT_MODEL, studentDTO);
        return new ResponseEntity&lt;String&gt;(&quot;/studentViews/addStudent&quot;, 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&lt;String&gt;(&quot;/studentViews/successStudentAddition&quot;, HttpStatus.Ok);
}

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:

确定