|
4 | 4 | */
|
5 | 5 | package org.hibernate.validator.test.spi.nodenameprovider;
|
6 | 6 |
|
| 7 | +import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertThat; |
| 8 | +import static org.hibernate.validator.testutil.ConstraintViolationAssert.violationOf; |
7 | 9 | import static org.testng.Assert.assertEquals;
|
8 | 10 |
|
9 | 11 | import java.lang.annotation.ElementType;
|
|
23 | 25 | import jakarta.validation.constraints.Size;
|
24 | 26 |
|
25 | 27 | import org.hibernate.validator.HibernateValidator;
|
| 28 | +import org.hibernate.validator.HibernateValidatorConfiguration; |
| 29 | +import org.hibernate.validator.cfg.ConstraintMapping; |
| 30 | +import org.hibernate.validator.cfg.defs.SizeDef; |
26 | 31 | import org.hibernate.validator.testutil.TestForIssue;
|
27 | 32 |
|
28 | 33 | import org.testng.annotations.BeforeMethod;
|
@@ -177,6 +182,30 @@ public void hibernateValidatorFallsBackToDefaultPropertyNodeNameProvider() {
|
177 | 182 | assertEquals( violation.getPropertyPath().toString(), "brand.name" );
|
178 | 183 | }
|
179 | 184 |
|
| 185 | + @Test |
| 186 | + public void constraintsDefinedProgrammatically() { |
| 187 | + HibernateValidatorConfiguration configuration = Validation.byProvider( HibernateValidator.class ) |
| 188 | + .configure() |
| 189 | + .propertyNodeNameProvider( new AnnotationPropertyNodeNameProvider( PropertyName.class ) ); |
| 190 | + ConstraintMapping constraintMapping = configuration.createConstraintMapping(); |
| 191 | + |
| 192 | + constraintMapping |
| 193 | + .type( ProgrammaticCar.class ) |
| 194 | + .field( "brand" ) |
| 195 | + .constraint( new SizeDef().min( 5 ).max( 50 ) ); |
| 196 | + |
| 197 | + ValidatorFactory validatorFactory = configuration |
| 198 | + .addMapping( constraintMapping ) |
| 199 | + .buildValidatorFactory(); |
| 200 | + |
| 201 | + Validator val = validatorFactory.getValidator(); |
| 202 | + |
| 203 | + assertThat( val.validate( new ProgrammaticCar( INVALID_BRAND_NAME ) ) ) |
| 204 | + .containsOnlyViolations( violationOf( Size.class ) |
| 205 | + .withProperty( "car_brand" ) ); |
| 206 | + |
| 207 | + } |
| 208 | + |
180 | 209 | @Retention(RetentionPolicy.RUNTIME)
|
181 | 210 | @Target({ ElementType.FIELD, ElementType.METHOD })
|
182 | 211 | public @interface PropertyName {
|
@@ -237,4 +266,13 @@ public Airplane(Engine engine) {
|
237 | 266 | this.engine = engine;
|
238 | 267 | }
|
239 | 268 | }
|
| 269 | + |
| 270 | + private static class ProgrammaticCar { |
| 271 | + @PropertyName("car_brand") |
| 272 | + public final String brand; |
| 273 | + |
| 274 | + ProgrammaticCar(String brand) { |
| 275 | + this.brand = brand; |
| 276 | + } |
| 277 | + } |
240 | 278 | }
|
0 commit comments