Skip to content

Instantly share code, notes, and snippets.

@Christopher-Barham-AKQA
Created September 7, 2012 12:16
Show Gist options
  • Save Christopher-Barham-AKQA/3665710 to your computer and use it in GitHub Desktop.
Save Christopher-Barham-AKQA/3665710 to your computer and use it in GitHub Desktop.
SomePojoValidatorTest.java unit test for Hibernate Validator
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.Locale;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class SomePojoTest {
class SomePojo {
private String text;
@NotNull
@Length(max = 100)
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
static Validator validator;
@BeforeClass
public static void before() throws Exception {
Locale.setDefault(Locale.ENGLISH);
ValidatorFactory config = Validation.buildDefaultValidatorFactory();
validator = config.getValidator();
}
Set<ConstraintViolation<SomePojo>> constraintViolations;
SomePojo somePojo;
@Before
public void setUp() throws Exception {
somePojo = new SomePojo();
somePojo.setText("XXX-ValidInputValue-XXX");
}
@Test
public void shouldFailValidationWithNullInputValuesForTextField() {
constraintViolations = validator.validateValue(SomePojo.class, "text", null);
assertThat("Text field should have a validation error for null input", constraintViolations.size(), is(1));
assertThat(constraintViolations.iterator().next().getMessage(), is("may not be null"));
}
@Test
public void shouldFailValidationWithOverLongInputValuesForTextField() {
// create a string made up of maxLength + 1 copies of the String "X"
String inputValue = String.format("%0" + 101 + "d", 0).replace("0", "X");
constraintViolations = validator.validateValue(SomePojo.class, "text", inputValue);
assertThat("Should Not get validation errors - input: " + inputValue + " issues: " + constraintViolations,
constraintViolations.size(), is(1));
}
@Test
public void shouldPassLengthValidationPropertyInputValuesForTextField() {
String inputValue = "SomeText";
constraintViolations = validator.validateValue(SomePojo.class, "text", inputValue);
assertThat("Should have got a validation error - input: " + inputValue, constraintViolations.size(), is(0));
}
@Test
public void testHappyPathValidationForWholeObject() {
constraintViolations = validator.validate(somePojo);
assertThat("validation failed: " + constraintViolations, constraintViolations.size(), is(0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment