Skip to content

Instantly share code, notes, and snippets.

@ufuk
Last active March 20, 2024 13:47
Show Gist options
  • Save ufuk/a644b333836226d89a0d432db73500d7 to your computer and use it in GitHub Desktop.
Save ufuk/a644b333836226d89a0d432db73500d7 to your computer and use it in GitHub Desktop.
How to initialize an instance of the constraint annotation while writing unit tests for a javax.validation.ConstraintValidator
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = ExampleConstraintValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExampleConstraint {
String message() default "{error.example_constraint.invalid}";
String customField() default "...";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ExampleConstraintValidator implements ConstraintValidator<ExampleConstraint, String> {
private String customField;
@Override
public void initialize(ExampleConstraint constraintAnnotation) {
this.customField = constraintAnnotation.customField();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
// Your business logic
}
}
import org.hibernate.validator.internal.util.annotation.AnnotationDescriptor;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
class ExampleConstraintValidatorTests {
@Test
void should...() {
final ExampleConstraintValidator exampleConstraintValidator = new ExampleConstraintValidator();
final ExampleConstraint exampleConstraint = new AnnotationDescriptor.Builder<>(ExampleConstraint.class, Collections.singletonMap("customField", "...")).build().getAnnotation();
exampleConstraintValidator.initialize(exampleConstraint);
assertThat(exampleConstraintValidator.isValid("...", null)).isTrue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment