Bean validation

Data validation is very important in enterprise applications to ensure data integrity. It allows us to check for possible data manipulation between the request made by the user and that received on the server side.

Let's take a look at an example of validating a Bean and writing a unit test to verify it. First, create a maven project:

  1.  Create a bean named Person that takes name, emailId, and preferredLanguage in its constructor. This is shown in the following code:
class Person(@field:NotBlank private val name:String,
@field:Email private val emailId:String,
@field:NotNull private val preferredLanguage:String)

Let's analyze what we have written for the Person bean. Take a look at how simple this class is.  All we have is a Person class with a constructor that takes name, emailId, and preferredLanguage as parameters to initialize the class. We used three annotations from the javax(javaee-api) library: @Email, @NotBlank, and @NonNull:

    • The @Email annotation ensures the emailId field accepts a String in the proper emailId format.
    • The @NotBlank annotation ensures the field name accepts a non-null value or a String that is not empty.
    • The @NotNull annotation ensures the preferredLanguage field accepts a non-null value.
  1. Write a Junit test to verify this, as follows:
class PersonTest {

@Test
fun validUser() {
val person = Person(
"Raghavendra Rao",
"[email protected]",
"en-us")

val validationErrors = PersonTest.validator
.validate(person)
Assert.assertTrue(validationErrors.isEmpty())
}

@Test
fun invalidName() {
val person = Person(
"",
"[email protected]",
"en-us")

val validationErrors = PersonTest.validator
.validate(person)
Assert.assertEquals(1, validationErrors.size.toLong())
}

@Test
fun invalidEmailId() {
val person = Person(
"Raghavendra Rao",
"kraghavendrarao1",
"en-us")

val validationErrors = PersonTest.validator
.validate(person)
Assert.assertEquals(1, validationErrors.size.toLong())
}

companion object {
private val validator: Validator = Validation.buildDefaultValidatorFactory()
.validator
}
}

PersonTest.kt is a simple Junit test class to verify the data-validation constraints defined in the Person bean class.

We are using a Validator class to validate the Person bean. The PersonTest.kt test class initializes the Person object and it verifies that the properties of the Person.kt class are valid.

In this section, we learned how to carry out bean validation using the javaee-api library. We also wrote a unit test to verify the data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset