Java Spring Boot中的完全验证测试,注入失败
大家好我想在我的Spring Boot应用程序中测试请求的完整验证我的意思是一次不测试一个验证器,而是在目标对象上测试所有验证器) 首先我有我的目标:Java Spring Boot中的完全验证测试,注入失败,java,unit-testing,validation,spring-boot,Java,Unit Testing,Validation,Spring Boot,大家好我想在我的Spring Boot应用程序中测试请求的完整验证我的意思是一次不测试一个验证器,而是在目标对象上测试所有验证器) 首先我有我的目标: public class UserCreationRequest { @JsonProperty("profileId") @NotNull @ValidProfile private Integer profileId; } 然后我的验证器(@ValidProfile): 在执行时,我可以看到,在测试本身中,注入工作
public class UserCreationRequest {
@JsonProperty("profileId")
@NotNull
@ValidProfile
private Integer profileId;
}
然后我的验证器(@ValidProfile):
在执行时,我可以看到,在测试本身中,注入工作:
restService被映射到“IUserRestService的模拟”
但在我的验证器中,它不是注入的,userRestService是空的
ProfileService也是这样
我尝试了这里看到的几件事情,没有任何效果(代码正在运行,只有testconf失败)这是因为您没有生成验证程序bean,所以它可以被注入 当您手动实例化LocalValidatorFactoryBean时,它无法访问为此测试定义的SpringDI 您应该为验证器生成一个bean,或者甚至引用一个现有的spring配置
@Component
public class ProfileValidator implements ConstraintValidator<ValidProfile, Integer> {
@Autowired
private IProfileService profileService;
@Autowired
private IUserRestService userRestService;
@Override
public void initialize(ValidProfile constraintAnnotation) {
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
RestUser restUser = userRestService.getRestUser();
ProfileEntity profileEntity = profileService.getProfile(value, restUser.getAccountId());
return profileEntity != null;
}
}
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {ValidationTestConfiguration.class})
public class UserCreationRequestValidationTest {
private static LocalValidatorFactoryBean localValidatorFactory;
@Autowired
private IUserService userService;
@Autowired
private IProfileService profileService;
@Autowired
private IUserRestService restService;
@BeforeClass
public static void createValidator() {
localValidatorFactory = new LocalValidatorFactoryBean();
localValidatorFactory.setProviderClass(HibernateValidator.class);
localValidatorFactory.afterPropertiesSet();
}
@AfterClass
public static void close() {
localValidatorFactory.close();
}
@Test
public void validateUserCreationRequestStringfields() {
UserCreationRequest userCreationRequest = new UserCreationRequest();
/* Here fill test object*/
when(userService.getUser(any(Integer.class), any(Integer.class))).thenReturn(new UserEntity());
when(profileService.getProfile(any(Integer.class), any(Integer.class))).thenReturn(new ProfileEntity());
when(restService.getRestUser()).thenReturn(new RestUser());
Set<ConstraintViolation<UserCreationRequest>> violations
= localValidatorFactory.validate(userCreationRequest);
assertEquals(violations.size(), 8);
}
}
@Configuration
public class ValidationTestConfiguration {
@Bean
@Primary
public IProfileService profileService() {
return Mockito.mock(IProfileService.class);
}
@Bean
@Primary
public IUserRestService userRestService() { return Mockito.mock(IUserRestService.class); }
}