/** * Validates the Bean Validation constraints specified at the parameters and/or return value of * the intercepted constructor. * * @param ctx The context of the intercepted constructor invocation. * @throws Exception Any exception caused by the intercepted constructor invocation. A {@link * ConstraintViolationException} in case at least one constraint violation occurred either * during parameter or return value validation. */ @AroundConstruct public void validateConstructorInvocation(InvocationContext ctx) throws Exception { ExecutableValidator executableValidator = validator.forExecutables(); Set<? extends ConstraintViolation<?>> violations = executableValidator.validateConstructorParameters( ctx.getConstructor(), ctx.getParameters()); if (!violations.isEmpty()) { throw new ConstraintViolationException( getMessage(ctx.getConstructor(), ctx.getParameters(), violations), violations); } ctx.proceed(); Object createdObject = ctx.getTarget(); violations = validator .forExecutables() .validateConstructorReturnValue(ctx.getConstructor(), createdObject); if (!violations.isEmpty()) { throw new ConstraintViolationException( getMessage(ctx.getConstructor(), ctx.getParameters(), violations), violations); } }
@Test public void shouldValidateParameterScriptAssertConstraintOnConstructor() throws Exception { ExecutableValidator executableValidator = getValidator().forExecutables(); Constructor<?> constructor = CalendarServiceImpl.class.getConstructor(String.class); Object[] parameterValues = new Object[] {"Foo"}; Set<ConstraintViolation<Object>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues); assertCorrectConstraintViolationMessages( violations, "script expression \"arg0.size() > 3\" didn't evaluate to true"); }
@Test public void shouldRaiseConstraintsViolationCauseTitleAndPriceNull() throws NoSuchMethodException { ExecutableValidator methodValidator = validator.forExecutables(); Constructor<Book03> constructor = Book03.class.getConstructor( String.class, Float.class, String.class, String.class, Integer.class, Boolean.class); Set<ConstraintViolation<Book03>> violations = methodValidator.validateConstructorParameters( constructor, new Object[] {null, null, null, null, null, null}); displayContraintViolations(violations); assertEquals(2, violations.size()); }
@Test public void shouldRaiseNoConstraintViolation() throws NoSuchMethodException { ExecutableValidator methodValidator = validator.forExecutables(); Constructor<Book03> constructor = Book03.class.getConstructor( String.class, Float.class, String.class, String.class, Integer.class, Boolean.class); Set<ConstraintViolation<Book03>> violations = methodValidator.validateConstructorParameters( constructor, new Object[] {"H2G2", 12.5f, "Best IT Scifi Book", "1234-4566-9876", 247, false}); assertEquals(0, violations.size()); }