How to test validation annotations of a class using JUnit?

The other answer saying that “the annotations do not do anything by themselves, you need to use a Validator to process the object” is correct, however, the answer lacks working instructions on how to do it using a Validator instance, which for me was what I really wanted.

Hibernate-validator is the reference implementation of such a validator. You can use it quite cleanly like this:

import static org.junit.Assert.assertFalse;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class ContactValidationTest {

    private Validator validator;

    public void setUp() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    public void testContactSuccess() {
        // I'd name the test to something like 
        // invalidEmailShouldFailValidation()

        Contact contact = new Contact();
        Set<ConstraintViolation<Contact>> violations = validator.validate(contact);

This assumes you have validator implementation and junit as dependencies.

Example of dependencies using Maven pom:


Leave a Comment