问题
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.
回答1:
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
回答2:
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>
来源:https://stackoverflow.com/questions/43725532/hibernate-validator-violation-message-language