So I followed the documentation on this page to make dependency injection in custom jsr validators work. As I understand it I need to add a LocalValidatorFactoryBean to my config, which I did here:
@Configuration
public class ValidatorConfig {
//Used to make sure custom validators get picked up
@Bean
public LocalValidatorFactoryBean validator(){
return new LocalValidatorFactoryBean();
}
}
This works in all my test-suites except for one:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = JpaConfig.class)
@ActiveProfiles(Profiles.TEST)
public class UserLifeCycleTestCase {
@Autowired
private UserJpaRepository userJpaRepository;
@Autowired
private CountryJpaRepository countryJpaRepository;
@Test
public void ageShouldBeCorrectBecauseEntityIsPeristed(){
User user = new User("robin.hellemans@realdolmen.com", "Robin0", "Robin", "Hellemans", new Date(), "Molenstraat", 82, "Londerzeel", "1840", countryJpaRepository.findOne(1L));
userJpaRepository.saveAndFlush(user);
assertNotNull(user.getPerson().getAge());
}
}
Relevant part of JpaConfig.class
:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.robin.repository")
@EnableJpaAuditing
//Picks up other @Configuration classes as well
@ComponentScan(basePackages = "com.robin")
public class JpaConfig {
In this testcase the JpaRepository (which is a Spring Data Jpa repository) is null. The validator: (I doubt there's anything wrong with it since other test cases also depend on this one and run successfully)
public class UniqueUserNameValidator implements ConstraintValidator<UniqueUserName, String>{
@Autowired
private UserJpaRepository userJpaRepository;
@Override
public void initialize(UniqueUserName constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return userJpaRepository.findByUserName(value) == null;
}
}
In my other test suits this is not the case, an example in which my repo's do get autowired:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = JpaConfig.class)
@ActiveProfiles(Profiles.TEST)
public class CountryValidationTestCase {
@Autowired
private Validator validator;
//Tests
Looking at the documentation, I did nothing wrong, so I really can't see the problem here.
Aucun commentaire:
Enregistrer un commentaire