generator.server.springboot.mvc.web.test.BeanValidationAssertions.mustache Maven / Gradle / Ivy
package {{packageName}};
import static org.assertj.core.api.Assertions.*;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import java.util.Set;
import java.util.function.Predicate;
import {{packageName}}.shared.error.domain.Assert;
public final class BeanValidationAssertions {
private BeanValidationAssertions() {}
public static BeanAsserter assertThatBean(T bean) {
return new BeanAsserter<>(bean);
}
public static final class BeanAsserter {
private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
private final Set> violations;
private BeanAsserter(T bean) {
Assert.notNull("bean", bean);
violations = validator.validate(bean);
}
public BeanAsserter isValid() {
assertThat(violations).isEmpty();
return this;
}
public InvalidPropertyAsserter hasInvalidProperty(String property) {
Assert.notBlank("property", property);
return violations
.stream()
.filter(withProperty(property))
.findFirst()
.map(validation -> new InvalidPropertyAsserter<>(this, validation))
.orElseThrow(() -> new AssertionError("Property " + property + " must be invalid and wasn't"));
}
private Predicate> withProperty(String property) {
return validation -> property.equals(validation.getPropertyPath().toString());
}
}
public static final class InvalidPropertyAsserter {
private final BeanAsserter beanAsserter;
private final ConstraintViolation violation;
@SuppressWarnings("java:S1144")
private InvalidPropertyAsserter(BeanAsserter beanAsserter, ConstraintViolation violation) {
this.beanAsserter = beanAsserter;
this.violation = violation;
}
public InvalidPropertyAsserter withMessage(String message) {
Assert.notBlank("message", message);
assertThat(violation.getMessage()).isEqualTo(message);
return this;
}
public InvalidPropertyAsserter withParameter(String parameter, Object value) {
Assert.notBlank("parameter", parameter);
assertThat(violation.getConstraintDescriptor().getAttributes()).contains(entry(parameter, value));
return this;
}
public BeanAsserter and() {
return beanAsserter;
}
}
}