Java 如何在型号验证spring boot中返回400状态

Java 如何在型号验证spring boot中返回400状态,java,spring,spring-boot,validation,junit,Java,Spring,Spring Boot,Validation,Junit,我想测试我的学生,以便: @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 stude

我想测试我的
学生,以便

@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;
}
学生控制器中的测试方法

@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个错误和上面确定的错误

e、 g.如果我通过了
studentAge=5
,我应该得到400个错误,并且信息:
学生年龄应该超过10岁
就像在
StudentDTO

中一样,我经常转向spring的org.springframework.http.ResponseEntity

@PostMapping(“successStudentAddition”)
public ResponseEntity addStudent(@ModelAttribute(“学生”)@Valid StudentDTO StudentDTO,Errors,Model Model){
if(errors.hasErrors()){
model.addAttribute(STUDENT\u model,studentDTO);
返回新的响应属性(“/studentViews/addStudent”,HttpStatus.BAD_请求);
}
Student Student=新学生(studentDTO.getStudentId(),studentDTO.getStudentName(),studentDTO.GetStudentNames(),
studentDTO.getStudentAge(),studentDTO.getEntryYear(),studentDTO.getGraduateYear(),studentDTO.getFacultyName(),
getGroupIdByName(studentDTO.getGroupName());
studentService.addStudent(学生);
返回新的响应属性(“/studentview/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);
    }
}
@ControllerAdvice
公共类错误处理程序{
@ExceptionHandler(值={MethodArgumentNotValidException.class})
公共响应无效ArgumentExceptionHandler(MethodArgumentNotValidException ex){
//您可以返回一些常规错误页面,而不是“/studentViews/successStudentAddition”。
返回新的响应属性(“/studentViews/successStudentAddition”,HttpStatus.BAD_请求);
}
}

好的,但我需要测试这个验证)我怎么做?
@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);
    }
}