3
votes

I have a test class where I am testing a domain model which is annotated with e.g. @NotNull

In my test class I am first getting the validator

private static Validator validator;

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

Later I have a JUnit Test where I am testing the domain model (lets say a Person)

Set<ConstraintViolation<Person>> violations = validator.validate( aPerson );

Lets say, I want to retrieve the first violation Message I do:

String violationMessage = violations.iterator().next().getMessage()

I haven't set any custom violation message on the @NotNull annotation. So hibernate validator will pull the default message from the Resource Bundle which is in the hibernate-validator-jar. My path looks like this:

hibernate-validator-5.3.5.Final.jar
    - org
        - hibernate
            - validator
                ...
                ResourceBundle 'Validation Messages'

In this Resource Bundle there are quite a few languages supported (English, German, French, ...)

Example

@NotNull violation message in German

javax.validation.constraints.NotNull.message     = darf nicht null sein

@NotNull violation message in English

javax.validation.constraints.NotNull.message     = may not be null

Question:

When I am testing, how can I enforce Hibernate Validator to choose a specific language for the violation message from the Resource Bundle? Right now, I am getting English violation messages. However, on another machine German.

3

3 Answers

6
votes

The answer of GKR is correct.

Additional information that might be useful: if you are using Maven and the surefire plugin, you need to do something like that:

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${maven-surefire-plugin.version}</version>
    <configuration>
        <forkMode>once</forkMode>
        <argLine>-Duser.language=en</argLine>
    </configuration>
</plugin>
1
votes

Summary condensed from the reference docs:

By default, the JVM's default locale (Locale#getDefault()) will be used when looking up messages in the bundle.

Without touching source code or fiddle with your OS/User seetings, try this for spanish messages:

java -Duser.country=ES -Duser.language=es

Hibernate Validator 5.1 Reference

0
votes

You can use the preparing part of your Testframework to set the default Locale and this will influence the language of your violation messages. In case you want to expect English, add

Locale.setDefault(Locale.ENGLISH);

before building your Validator Factory. Might look like this in your example:

private static Validator validator;

@BeforeClass
public static void setup() {
    Locale.setDefault(Locale.ENGLISH);
    validator = Validation.buildDefaultValidatorFactory().getValidator();
}