Merge branch 'master' into javabeanconstraints

This commit is contained in:
Alejandro Gervasio
2018-09-22 17:33:13 -03:00
committed by GitHub
8553 changed files with 788097 additions and 43990 deletions

View File

@@ -7,3 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation)
- [Validating Container Elements with Bean Validation 2.0](http://www.baeldung.com/bean-validation-container-elements)
- [Method Constraints with Bean Validation 2.0](http://www.baeldung.com/javax-validation-method-constraints)

View File

@@ -1,6 +0,0 @@
.classpath
.project
.settings/
target/

View File

@@ -1,44 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>javaxval</artifactId>
<version>0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,66 @@
package org.baeldung;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.PositiveOrZero;
public class Customer {
@NotBlank(message="Name cannot be empty")
private String name;
private List<@NotBlank(message="Address must not be blank") String> addresses;
private Integer age;
@PositiveOrZero
private OptionalInt numberOfOrders;
//@NotBlank
private Profile profile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public Optional<@Min(18) Integer> getAge() {
return Optional.ofNullable(age);
}
public void setAge(Integer age) {
this.age = age;
}
public OptionalInt getNumberOfOrders() {
return numberOfOrders;
}
public void setNumberOfOrders(OptionalInt numberOfOrders) {
this.numberOfOrders = numberOfOrders;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}

View File

@@ -0,0 +1,19 @@
package org.baeldung;
import java.util.Map;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
public class CustomerMap {
private Map<@Email(message="Must be a valid email") String, @NotNull Customer> customers;
public Map<String, Customer> getCustomers() {
return customers;
}
public void setCustomers(Map<String, Customer> customers) {
this.customers = customers;
}
}

View File

@@ -0,0 +1,13 @@
package org.baeldung;
public class Profile {
private String companyName;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
}

View File

@@ -1,56 +1,94 @@
package org.baeldung;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import javax.validation.constraints.NotBlank;
public class User {
@NotNull(message = "Name cannot be null")
private String name;
@NotNull(message = "Name cannot be null")
private String name;
@AssertTrue
private boolean working;
@AssertTrue
private boolean working;
@Size(min = 10, max = 200, message = "Number of characters should be in between 10 and 200 inclusive")
private String aboutMe;
@Size(min = 10, max = 200, message = "Number of characters should be in between 10 and 200 inclusive")
private String aboutMe;
@Min(value = 18, message = "Age should not be less than 18")
@Max(value = 150, message = "Age should not be more than 150")
private int age;
@Min(value = 18, message = "Age should not be less than 18")
@Max(value = 150, message = "Age should not be more than 150")
private int age;
public int getAge() {
return age;
}
@Email(message = "Email should be valid")
private String email;
List<@NotBlank String> preferences;
private LocalDate dateOfBirth;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public boolean isWorking() {
return working;
}
public void setAge(int age) {
this.age = age;
}
public void setWorking(boolean working) {
this.working = working;
}
public boolean isWorking() {
return working;
}
public String getAboutMe() {
return aboutMe;
}
public void setWorking(boolean working) {
this.working = working;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
public String getAboutMe() {
return aboutMe;
}
public String getName() {
return name;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Optional<@Past LocalDate> getDateOfBirth() {
return Optional.ofNullable(dateOfBirth);
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<String> getPreferences() {
return preferences;
}
public void setPreferences(List<String> preferences) {
this.preferences = preferences;
}
}

View File

@@ -0,0 +1,38 @@
package org.baeldung.javaxval.methodvalidation;
import org.baeldung.javaxval.methodvalidation.model.Customer;
import org.baeldung.javaxval.methodvalidation.model.Reservation;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import java.time.LocalDate;
@Configuration
@ComponentScan({ "org.baeldung.javaxval.methodvalidation.model" })
public class MethodValidationConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
@Bean("customer")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Customer customer(String firstName, String lastName) {
Customer customer = new Customer(firstName, lastName);
return customer;
}
@Bean("reservation")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Reservation reservation(LocalDate begin, LocalDate end, Customer customer, int room) {
Reservation reservation = new Reservation(begin, end, customer, room);
return reservation;
}
}

View File

@@ -0,0 +1,25 @@
package org.baeldung.javaxval.methodvalidation.constraints;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraintvalidation.SupportedValidationTarget;
import javax.validation.constraintvalidation.ValidationTarget;
import java.time.LocalDate;
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class ConsistentDateParameterValidator implements ConstraintValidator<ConsistentDateParameters, Object[]> {
@Override
public boolean isValid(Object[] value, ConstraintValidatorContext context) {
if (value[0] == null || value[1] == null) {
return true;
}
if (!(value[0] instanceof LocalDate) || !(value[1] instanceof LocalDate)) {
throw new IllegalArgumentException("Illegal method signature, expected two parameters of type LocalDate.");
}
return ((LocalDate) value[0]).isAfter(LocalDate.now()) && ((LocalDate) value[0]).isBefore((LocalDate) value[1]);
}
}

View File

@@ -0,0 +1,23 @@
package org.baeldung.javaxval.methodvalidation.constraints;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Constraint(validatedBy = ConsistentDateParameterValidator.class)
@Target({ METHOD, CONSTRUCTOR })
@Retention(RUNTIME)
@Documented
public @interface ConsistentDateParameters {
String message() default "End date must be after begin date and both must be in the future";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@@ -0,0 +1,24 @@
package org.baeldung.javaxval.methodvalidation.constraints;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Constraint(validatedBy = ValidReservationValidator.class)
@Target({ METHOD, CONSTRUCTOR })
@Retention(RUNTIME)
@Documented
public @interface ValidReservation {
String message() default "End date must be after begin date and both must be in the future, room number must be bigger than 0";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@@ -0,0 +1,32 @@
package org.baeldung.javaxval.methodvalidation.constraints;
import org.baeldung.javaxval.methodvalidation.model.Reservation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDate;
public class ValidReservationValidator implements ConstraintValidator<ValidReservation, Reservation> {
@Override
public boolean isValid(Reservation reservation, ConstraintValidatorContext context) {
if (reservation == null) {
return true;
}
if (!(reservation instanceof Reservation)) {
throw new IllegalArgumentException("Illegal method signature, expected parameter of type Reservation.");
}
if (reservation.getBegin() == null || reservation.getEnd() == null || reservation.getCustomer() == null) {
return false;
}
return (reservation.getBegin()
.isAfter(LocalDate.now())
&& reservation.getBegin()
.isBefore(reservation.getEnd())
&& reservation.getRoom() > 0);
}
}

View File

@@ -0,0 +1,41 @@
package org.baeldung.javaxval.methodvalidation.model;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Validated
public class Customer {
@Size(min = 5, max = 200)
private String firstName;
@Size(min = 5, max = 200)
private String lastName;
public Customer(@Size(min = 5, max = 200) @NotNull String firstName, @Size(min = 5, max = 200) @NotNull String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Customer() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@@ -0,0 +1,64 @@
package org.baeldung.javaxval.methodvalidation.model;
import org.baeldung.javaxval.methodvalidation.constraints.ConsistentDateParameters;
import org.baeldung.javaxval.methodvalidation.constraints.ValidReservation;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.Positive;
import java.time.LocalDate;
@Validated
public class Reservation {
private LocalDate begin;
private LocalDate end;
@Valid
private Customer customer;
@Positive
private int room;
@ConsistentDateParameters
@ValidReservation
public Reservation(LocalDate begin, LocalDate end, Customer customer, int room) {
this.begin = begin;
this.end = end;
this.customer = customer;
this.room = room;
}
public LocalDate getBegin() {
return begin;
}
public void setBegin(LocalDate begin) {
this.begin = begin;
}
public LocalDate getEnd() {
return end;
}
public void setEnd(LocalDate end) {
this.end = end;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public int getRoom() {
return room;
}
public void setRoom(int room) {
this.room = room;
}
}

View File

@@ -0,0 +1,50 @@
package org.baeldung.javaxval.methodvalidation.model;
import org.baeldung.javaxval.methodvalidation.constraints.ConsistentDateParameters;
import org.baeldung.javaxval.methodvalidation.constraints.ValidReservation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.time.LocalDate;
import java.util.List;
@Controller
@Validated
public class ReservationManagement {
@Autowired
private ApplicationContext applicationContext;
@ConsistentDateParameters
public void createReservation(LocalDate begin, LocalDate end, @NotNull Customer customer) {
// ...
}
public void createReservation(@NotNull @Future LocalDate begin, @Min(1) int duration, @NotNull Customer customer) {
// ...
}
public void createReservation(@Valid Reservation reservation) {
// ...
}
@NotNull
@Size(min = 1)
public List<@NotNull Customer> getAllCustomers() {
return null;
}
@Valid
public Reservation getReservationById(int id) {
return null;
}
}

View File

@@ -0,0 +1,17 @@
package org.baeldung.valueextractors;
import javax.validation.valueextraction.ExtractedValue;
import javax.validation.valueextraction.UnwrapByDefault;
import javax.validation.valueextraction.ValueExtractor;
import org.baeldung.Profile;
@UnwrapByDefault
public class ProfileValueExtractor implements ValueExtractor<@ExtractedValue(type = String.class) Profile> {
@Override
public void extractValues(Profile originalValue, ValueExtractor.ValueReceiver receiver) {
receiver.value(null, originalValue.getCompanyName());
}
}

View File

@@ -0,0 +1 @@
org.baeldung.valueextractors.ProfileValueExtractor

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,88 @@
package org.baeldung;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.OptionalInt;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.baeldung.valueextractors.ProfileValueExtractor;
import org.junit.Before;
import org.junit.Test;
public class ContainerValidationIntegrationTest {
private Validator validator;
@Before
public void setup() {
ValidatorFactory factory = Validation.byDefaultProvider().configure()
.addValueExtractor(new ProfileValueExtractor()).buildValidatorFactory();
validator = factory.getValidator();
}
@Test
public void whenEmptyAddress_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
customer.setAddresses(Collections.singletonList(" "));
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
assertEquals("Address must not be blank", violations.iterator()
.next()
.getMessage());
}
@Test
public void whenInvalidEmail_thenValidationFails() {
CustomerMap map = new CustomerMap();
map.setCustomers(Collections.singletonMap("john", new Customer()));
Set<ConstraintViolation<CustomerMap>> violations = validator.validate(map);
assertEquals(1, violations.size());
assertEquals("Must be a valid email", violations.iterator()
.next()
.getMessage());
}
@Test
public void whenAgeTooLow_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
customer.setAge(15);
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
}
@Test
public void whenAgeNull_thenValidationSucceeds() {
Customer customer = new Customer();
customer.setName("John");
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(0, violations.size());
}
@Test
public void whenNumberOrdersValid_thenValidationSucceeds() {
Customer customer = new Customer();
customer.setName("John");
customer.setNumberOfOrders(OptionalInt.of(1));
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(0, violations.size());
}
//@Test
public void whenProfileCompanyNameBlank_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
Profile profile = new Profile();
profile.setCompanyName(" ");
customer.setProfile(profile);
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
}
}

View File

@@ -1,81 +1,126 @@
package org.baeldung;
import java.time.LocalDate;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.Optional;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
public class ValidationIntegrationTest {
@Test
public void ifNameIsNull_nameValidationFails() {
User user = new User();
user.setWorking(true);
user.setAboutMe("Its all about me!!");
user.setAge(50);
private Validator validator;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
}
@Before
public void setup() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void ifSizeNotInRange_aboutMeValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(50);
private User createUser() {
User user = new User();
user.setName("John");
user.setWorking(true);
user.setAge(18);
return user;
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
}
@Test
public void ifNameIsNull_nameValidationFails() {
User user = new User();
user.setWorking(true);
user.setAboutMe("Its all about me!!");
user.setAge(50);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
}
@Test
public void ifWorkingIsFalse_workingValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(50);
@Test
public void ifSizeNotInRange_aboutMeValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(50);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
}
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
}
@Test
public void ifAgeNotRange_ageValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(8);
@Test
public void ifWorkingIsFalse_workingValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(50);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
}
@Test
public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() {
User user = new User();
user.setAboutMe("Its all about me!!");
user.setAge(300);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
Assert.assertEquals(violations.isEmpty(), false);
Assert.assertEquals(violations.size(), 3);
}
@Test
public void ifAgeNotRange_ageValidationFails() {
User user = new User();
user.setName("MyName");
user.setAboutMe("Its all about me!!");
user.setAge(8);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
}
@Test
public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() {
User user = new User();
user.setAboutMe("Its all about me!!");
user.setAge(300);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(violations.isEmpty(), false);
assertEquals(violations.size(), 3);
}
@Test
public void givenInvalidEmail_thenValidationFails() {
User user = createUser();
user.setEmail("john");
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(1, violations.size());
}
@Test
public void givenBlankPreference_thenValidationFails() {
User user = createUser();
user.setPreferences(Collections.singletonList(" "));
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(1, violations.size());
}
@Test
public void givenEmptyOptional_thenValidationSucceeds() {
User user = createUser();
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(0, violations.size());
}
@Test
public void givenPastDateOfBirth_thenValidationSuccess() {
User user = createUser();
user.setDateOfBirth(LocalDate.of(1980, 5, 20));
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(0, violations.size());
}
}

View File

@@ -0,0 +1,97 @@
package org.baeldung.javaxval.methodvalidation;
import org.baeldung.javaxval.methodvalidation.model.Customer;
import org.baeldung.javaxval.methodvalidation.model.Reservation;
import org.baeldung.javaxval.methodvalidation.model.ReservationManagement;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.validation.ConstraintViolationException;
import java.time.LocalDate;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MethodValidationConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ContainerValidationIntegrationTest {
@Autowired
ReservationManagement reservationManagement;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void whenValidationWithInvalidMethodParameters_thenConstraintViolationException() {
exception.expect(ConstraintViolationException.class);
reservationManagement.createReservation(LocalDate.now(), 0, null);
}
@Test
public void whenValidationWithValidMethodParameters_thenNoException() {
reservationManagement.createReservation(LocalDate.now()
.plusDays(1), 1, new Customer("William", "Smith"));
}
@Test
public void whenCrossParameterValidationWithInvalidParameters_thenConstraintViolationException() {
exception.expect(ConstraintViolationException.class);
reservationManagement.createReservation(LocalDate.now(), LocalDate.now(), null);
}
@Test
public void whenCrossParameterValidationWithValidParameters_thenNoException() {
reservationManagement.createReservation(LocalDate.now()
.plusDays(1),
LocalDate.now()
.plusDays(2),
new Customer("William", "Smith"));
}
@Test
public void whenValidationWithInvalidReturnValue_thenConstraintViolationException() {
exception.expect(ConstraintViolationException.class);
List<Customer> list = reservationManagement.getAllCustomers();
}
@Test
public void whenValidationWithInvalidCascadedValue_thenConstraintViolationException() {
Customer customer = new Customer();
customer.setFirstName("John");
customer.setLastName("Doe");
Reservation reservation = new Reservation(LocalDate.now()
.plusDays(1),
LocalDate.now()
.plusDays(2),
customer, 1);
exception.expect(ConstraintViolationException.class);
reservationManagement.createReservation(reservation);
}
@Test
public void whenValidationWithValidCascadedValue_thenCNoException() {
Customer customer = new Customer();
customer.setFirstName("William");
customer.setLastName("Smith");
Reservation reservation = new Reservation(LocalDate.now()
.plusDays(1),
LocalDate.now()
.plusDays(2),
customer, 1);
reservationManagement.createReservation(reservation);
}
}

View File

@@ -0,0 +1,209 @@
package org.baeldung.javaxval.methodvalidation;
import org.baeldung.javaxval.methodvalidation.model.Customer;
import org.baeldung.javaxval.methodvalidation.model.Reservation;
import org.baeldung.javaxval.methodvalidation.model.ReservationManagement;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.Collections;
import java.util.Set;
public class ValidationIntegrationTest {
private ExecutableValidator executableValidator;
@Before
public void getExecutableValidator() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
this.executableValidator = factory.getValidator()
.forExecutables();
}
@Test
public void whenValidationWithInvalidMethodParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
ReservationManagement object = new ReservationManagement();
Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, int.class, Customer.class);
Object[] parameterValues = { LocalDate.now(), 0, null };
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
assertEquals(3, violations.size());
}
@Test
public void whenValidationWithValidMethodParameters_thenZeroVoilations() throws NoSuchMethodException {
ReservationManagement object = new ReservationManagement();
Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, int.class, Customer.class);
Object[] parameterValues = { LocalDate.now()
.plusDays(1), 1, new Customer("John", "Doe") };
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
assertEquals(0, violations.size());
}
@Test
public void whenCrossParameterValidationWithInvalidParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
ReservationManagement object = new ReservationManagement();
Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, LocalDate.class, Customer.class);
Object[] parameterValues = { LocalDate.now(), LocalDate.now(), new Customer("John", "Doe") };
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
assertEquals(1, violations.size());
}
@Test
public void whenCrossParameterValidationWithValidParameters_thenZeroVoilations() throws NoSuchMethodException {
ReservationManagement object = new ReservationManagement();
Method method = ReservationManagement.class.getMethod("createReservation", LocalDate.class, LocalDate.class, Customer.class);
Object[] parameterValues = { LocalDate.now()
.plusDays(1),
LocalDate.now()
.plusDays(2),
new Customer("John", "Doe") };
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
assertEquals(0, violations.size());
}
@Test
public void whenValidationWithInvalidConstructorParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
Constructor<Customer> constructor = Customer.class.getConstructor(String.class, String.class);
Object[] parameterValues = { "John", "Doe" };
Set<ConstraintViolation<Customer>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues);
assertEquals(2, violations.size());
}
@Test
public void whenValidationWithValidConstructorParameters_thenZeroVoilations() throws NoSuchMethodException {
Constructor<Customer> constructor = Customer.class.getConstructor(String.class, String.class);
Object[] parameterValues = { "William", "Smith" };
Set<ConstraintViolation<Customer>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues);
assertEquals(0, violations.size());
}
@Test
public void whenCrossParameterValidationWithInvalidConstructorParameters_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class);
Object[] parameterValues = { LocalDate.now(), LocalDate.now(), new Customer("William", "Smith"), 1 };
Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues);
assertEquals(1, violations.size());
}
@Test
public void whenCrossParameterValidationWithValidConstructorParameters_thenZeroVoilations() throws NoSuchMethodException {
Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class);
Object[] parameterValues = { LocalDate.now()
.plusDays(1),
LocalDate.now()
.plusDays(2),
new Customer("William", "Smith"), 1 };
Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorParameters(constructor, parameterValues);
assertEquals(0, violations.size());
}
@Test
public void whenValidationWithInvalidReturnValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
ReservationManagement object = new ReservationManagement();
Method method = ReservationManagement.class.getMethod("getAllCustomers");
Object returnValue = Collections.<Customer> emptyList();
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateReturnValue(object, method, returnValue);
assertEquals(1, violations.size());
}
@Test
public void whenValidationWithValidReturnValue_thenZeroVoilations() throws NoSuchMethodException {
ReservationManagement object = new ReservationManagement();
Method method = ReservationManagement.class.getMethod("getAllCustomers");
Object returnValue = Collections.singletonList(new Customer("William", "Smith"));
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateReturnValue(object, method, returnValue);
assertEquals(0, violations.size());
}
@Test
public void whenValidationWithInvalidConstructorReturnValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class);
Reservation createdObject = new Reservation(LocalDate.now(), LocalDate.now(), new Customer("William", "Smith"), 0);
Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject);
assertEquals(1, violations.size());
}
@Test
public void whenValidationWithValidConstructorReturnValue_thenZeroVoilations() throws NoSuchMethodException {
Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class);
Reservation createdObject = new Reservation(LocalDate.now()
.plusDays(1),
LocalDate.now()
.plusDays(2),
new Customer("William", "Smith"), 1);
Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject);
assertEquals(0, violations.size());
}
@Test
public void whenValidationWithInvalidCascadedValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
ReservationManagement object = new ReservationManagement();
Method method = ReservationManagement.class.getMethod("createReservation", Reservation.class);
Customer customer = new Customer();
customer.setFirstName("John");
customer.setLastName("Doe");
Reservation reservation = new Reservation(LocalDate.now()
.plusDays(1),
LocalDate.now()
.plusDays(2),
customer, 1);
Object[] parameterValues = { reservation };
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
assertEquals(2, violations.size());
}
@Test
public void whenValidationWithValidCascadedValue_thenCorrectNumberOfVoilations() throws NoSuchMethodException {
ReservationManagement object = new ReservationManagement();
Method method = ReservationManagement.class.getMethod("createReservation", Reservation.class);
Customer customer = new Customer();
customer.setFirstName("William");
customer.setLastName("Smith");
Reservation reservation = new Reservation(LocalDate.now()
.plusDays(1),
LocalDate.now()
.plusDays(2),
customer, 1);
Object[] parameterValues = { reservation };
Set<ConstraintViolation<ReservationManagement>> violations = executableValidator.validateParameters(object, method, parameterValues);
assertEquals(0, violations.size());
}
}