使用Constraintvalidator验证国家/地区代码,该内部代码调用Rest服务。 CountryCodeValueValidator:
public class CountryCodeValueValidator
implements ConstraintValidator<CountryCodeValidator, Object> {
@Override
public void initialize(CountryCodeValidator countryCodeValidator) {
}
@Autowired
private CountryCodeClient countryCodeClient;
public void setCountryCodeClient(CountryCodeClient countryCodeClient) {
this.countryCodeClient = countryCodeClient;
}
@Override
public boolean isValid(Object countryCode,
ConstraintValidatorContext constraintValidatorContext) {
if (countryCode == null) {
return true;
}
String country = (String) countryCode;
return countryCodeClient
.getCountry(country)
.getStatusCode()
.is2xxSuccessful();
}
}
CountryCodeValidator:
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CountryCodeValueValidator.class)
@Documented
public @interface CountryCodeValidator {
String message() default "{people.address_invalid_country}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented @interface List {
CountryCodeValidator[] value();
}
测试用例:
@RunWith(MockitoJUnitRunner.class)
@Category(Small.class) 公共类CountryValidationTest {
ValidatorFactory validatorFactory;
@Mock
CountryCodeClient countryCodeClient;
@InjectMocks
CountryCodeValueValidator countryCodeValueValidator;
@Before
public void setUp() throws Exception {
//countryCodeClient = mock(CountryCodeClient.class);
validatorFactory = Validation.buildDefaultValidatorFactory();
}
@After
public void tearDown() throws Exception {
validatorFactory.close();
}
@Test
public void test() throws Exception {
Country country = new CountryBuilder().setCode("ABC3173EF24").createCountry();
Validator validator = validatorFactory.getValidator();
Mockito.when(countryCodeClient.getCountry("USA")).thenReturn(ok().build());
assertMessage(
"country_code_invalid",
validator.validate(country)
);
}
抛出NullpointerException。
我找到了以下链接。但我没有得到如何使用它们 spring 3 autowiring and junit testing