3

I can't seem to get a custom validation message to work. First I tried it with a custom validator, but it didn't work there, so following this example, I tried using a built-in constraint with custom message key, but no luck.

Here's my JUnit4 test case for the problem:

public class PatternMessageTest {
    private static Validator validator;

    @BeforeClass
    public static void setUp() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    @Test
    public void testIsValid_invalid() {
        StringHolder stringHolder = new StringHolder();
        stringHolder.setSomeString("not digits");

        Set<ConstraintViolation<StringHolder>> constraintViolations = validator.validate(stringHolder);
            assertEquals(1, constraintViolations.size());
            assertEquals(
                "Some validation message", 
                constraintViolations.iterator().next().getMessage());
    }

    private class StringHolder {
        @Valid
        @Pattern(regexp="\\d+", message="{mymessagekey}")
        private String _someString;

        // _someString getter, setter
    }

}

Here is the contents of ValidationMessages.properties, which is in the root of my test directory:

mymessagekey=Some validation message

The test output is:

org.junit.ComparisonFailure: expected:<[Some validation message]> but was:<[{mymessagekey}]>

So the message key is apparently not being located. What am I doing wrong?

Relevant classpath:

  • validation-api-1.0.0.GA.jar
  • hibernate-validator-4.1.0.Final.jar
  • hibernate-validator-annotation-processor-4.1.0.Final.jar

Before getting down to such a simple test case, I was adding validation to a Spring MVC app, and the behavior is the same: I keep getting the key with surrounding braces as the message returned by validation.

Community
  • 1
  • 1
Mike Partridge
  • 5,128
  • 8
  • 35
  • 47
  • *"which is in the root of my `test` directory"*, is that directory part of the classpath? – BalusC Sep 10 '12 at 02:33
  • `test` is a source folder in Eclipse, and ValidationMessages.properties ends up in bin/ alongside the compiled package directory structure. – Mike Partridge Sep 10 '12 at 02:35

0 Answers0