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.