我不知道如何为自定义约束验证器编写单元测试。我有以下验证器类:
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class SchoolIdValidator implements ConstraintValidator<ValidSchoolId, String> {
private SchoolService schoolService;
@Override
public void initialize(ValidSchoolId constraintAnnotation) {}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
return schoolService.isValidSchoolId(s);
}
}
Validator 由以下注释使用:
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SchoolIdValidator.class)
public @interface ValidSchoolId {
String message() default "Must be a valid school. Found: ${validatedValue}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
SchoolService
是一个使用 ApiClient 调用 School Api 的类,ApiClient 是一个具有通用 restTemplate 请求的通用类:
@Service
@AllArgsConstructor
public class SchoolService {
private ApiClient apiSchoolClient;
public Boolean isValidSchoolId(String schoolId){
try {
ResponseEntity res = apiSchoolClient.get(
String.format("/stores/%s", schoolId), Object.class, null);
return res.getStatusCode().is2xxSuccessful();
} catch (HttpClientErrorException e) {
if(e.getStatusCode().value() == 404)
return false;
else
throw new TechnicalException("Can't get response from school Api");
} catch(RestClientException e) {
throw new TechnicalException("Can't get response from School Api");
}
}
}
最后是学生课:
@Data
public class Student {
private String id;
private String firstName;
private String lastName;
@ValidSchoolId
private String schoolId;
}
当我运行该应用程序时,它可以完美运行。但是,它根本不适用于以下 Test 类:
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(SpringExtension.class)
public class SchoolIdValidatorTest {
Validator validator;
@InjectMocks
private SchoolService schoolService;
@Mock
private ApiClient apiSchoolClient;
@Before
public void setUp() throws Exception {
validator = Validation.buildDefaultValidatorFactory().getValidator();
MockitoAnnotations.initMocks(this);
}
@Test
public void isValid_SchoolIdExists_ShouldValidate() {
Mockito.when(this.apiSchoolClient.get(Mockito.eq("/schools/12"), Mockito.any(), Mockito.any()))
.thenReturn(new ResponseEntity<>(HttpStatus.OK));
//given
Student student = new Student();
simulation.setSchoolId("12");
//when
Set<ConstraintViolation<Student>> violations = validator.validate(student);
//then
assertEquals(0, violations.size());
}
当它进来的时候SchoolIdValidator
schoolService
总是null
。因此,它总是在 SchoolIdValidator.isValid 上抛出 NPE。如果有人有解决方案,那将非常有帮助。
感谢您的阅读和帮助。