【问题标题】:How to return 400 status in model validation spring boot如何在模型验证spring boot中返回400状态
【发布时间】:2020-10-15 18:33:27
【问题描述】:

我想测试我的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 中一样。

【问题讨论】:

    标签: java spring spring-boot validation junit


    【解决方案1】:

    我经常求助于spring的org.springframework.http.ResponseEntityclass

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

    【讨论】:

    • 好的,但我需要测试这个验证)我该怎么做?
    【解决方案2】:

    当你有这种情况时,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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 2012-05-03
      相关资源
      最近更新 更多