カスタム制約バリデーターの単体テストを作成する方法がわかりません。次の Validator クラスがあります。
@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
Generic restTemplate requests を持つ Generic クラスである ApiClient を使用して School Api を呼び出すクラスです。
@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");
}
}
}
そして最後に Student クラス:
@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 をスローします。誰かが解決策を持っていれば、それは本当に役に立ちます。
読んで助けてくれてありがとう。