I’m trying to write some tests using FixtureMonkey, and I’ve encountered an issue. My DTOs have custom validators, and I’m using JakartaValidationPlugin
with FixtureMonkey.
Here’s a simplified version of my test setup:
@SpringBootTest
@DisplayName("User Service Tests")
class UserServiceTest {
private static final FixtureMonkey fixtureMonkey = FixtureMonkey.builder()
.objectIntrospector(FieldReflectionArbitraryIntrospector.INSTANCE)
.plugin(new JakartaValidationPlugin())
.defaultNotNull(true)
.build();
private static ResponseUserDto expectedResponseDto;
private static RequestUserDto expectedRequestDto;
@BeforeAll
static void setUp() {
expectedResponseDto = fixtureMonkey.giveMeOne(ResponseUserDto.class);
expectedRequestDto = fixtureMonkey.giveMeOne(RequestUserDto.class);
}
}
The issue arises because some of my validators depend on a repository for validation logic. For example, I have a custom UniqueEmailValidator
like this:
@Component
public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {
private final UserRepository userRepository;
@Autowired
public UniqueEmailValidator(final UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public boolean isValid(final String email, final ConstraintValidatorContext context) {
if (email == null) {
return true;
}
return !userRepository.existsByEmail(email);
}
}
When I run the tests, I get the following error:
HV000064: Unable to instantiate ConstraintValidator: my.awesome.package.validation.UniqueEmailValidator.
jakarta.validation.ValidationException: HV000064: Unable to instantiate ConstraintValidator: my.awesome.package.validation.UniqueEmailValidator.
at org.hibernate.validator.internal.util.privilegedactions.NewInstance.run(NewInstance.java:44)
my.awesome.package.validation.UniqueEmailValidator.<init>()
java.lang.NoSuchMethodException: my.awesome.package.validation.UniqueEmailValidator.<init>()
What I’ve Learned So Far
I understand that this error occurs because FixtureMonkey invokes Jakarta Validation when generating the DTOs, and the validator’s constructor requires a UserRepository
(via @Autowired), which isn’t initialized in this context.
My Goal
I’d like to disable or bypass specific validations (e.g., UniqueEmailValidator) when generating data with FixtureMonkey. I’m looking for the best way to achieve this while keeping the rest of the validation logic intact.
What’s the recommended approach to handle this situation? Should I configure FixtureMonkey, mock the validator, or is there another solution?
I also asked a question on GitHub to FixtureMonkey, and the answer turned out to be quite simple and straightforward.