Last active
March 20, 2024 13:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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