Unit Testing Validation in Annotation Based Validating Spring Beans

Friday, April 22nd, 2011


I added validation, via annotations, to a Spring “Model” bean. I needed someway to Unit Test this validation, without running the container and without initialising the Spring context.

The bean (simplified)

package foo.bar;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public final class ProductModel {
    @Pattern(regexp="[^\n^\t^\r]+", message="Long Name must not contain New Lines, Carriage Returns or Tabs")
    private String longName;

    private String shortName;

    // rest snipped for brevity

The Unit Test

package foo.bar;

import java.util.Set;

import javax.validation.ConstraintViolation;

import junit.framework.Assert;

import org.hibernate.validator.HibernateValidator;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

public class Temp {
    private LocalValidatorFactoryBean localValidatorFactory;
    public void setup() {
        localValidatorFactory = new LocalValidatorFactoryBean();
    public void testLongNameWithInvalidCharCausesValidationError() {
        final ProductModel productModel = new ProductModel();
        productModel.setLongName("A long name with\t a Tab character");
    	Set<ConstraintViolation<ProductModel>> constraintViolations = localValidatorFactory.validate(productModel);
    	Assert.assertTrue("Expected validation error not found", constraintViolations.size() == 1);


It actually took me a few hours to work the above test out (simple as it is). If I hadn’t stumbled upon these Spring Unit Tests, I might never have got it.

You can leave a response, or trackback from your own site.

Tags: , , , ,
Posted in: Spring

3 Responses to “Unit Testing Validation in Annotation Based Validating Spring Beans”

  1. Per Wramdemark Says:

    September 24th, 2012 at 7:32 pm

    Thanks, just what I was looking for!

  2. Michael R Says:

    September 17th, 2013 at 7:48 pm

    Thanks, works great for testing Annotation Based validations 🙂

  3. setareh Says:

    February 5th, 2016 at 4:02 pm

    Perfect!! Thanks

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>