【发布时间】: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