Hibernate Validator:违规消息语言

Hibernate Validator: Violation Message Language

我有一个测试 class 我正在测试一个域模型,该模型用例如注释@NotNull

在我的测试中class我首先得到验证器

private static Validator validator;

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

稍后我有一个 JUnit 测试,我在其中测试域模型(比如说一个人)

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

比方说,我想检索我执行的第一条违规消息:

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

我没有在@NotNull 注释上设置任何自定义违规消息。因此,hibernate 验证器将从 hibernate-validator-jar 中的 Resource Bundle 中提取默认消息。我的路径如下所示:

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

在此资源包中,支持多种语言(英语、德语、法语……)

例子

@NotNull 德语违规消息

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

@NotNull 英文违规留言

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

问题:

测试时,如何强制 Hibernate Validator 为资源包中的违规消息选择特定语言?现在,我收到了英语违规信息。但是,在另一台机器上德语。

参考文档的摘要:

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

在不触及源代码或 fiddle 的情况下使用 OS/User 设置,试试这个西班牙语消息:

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

Hibernate Validator 5.1 Reference

GKR 的答案是正确的。

可能有用的其他信息:如果您正在使用 Maven 和 surefire 插件,则需要执行类似的操作:

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

您可以使用测试框架的准备部分来设置默认语言环境,这将影响违规消息的语言。如果您希望使用英语,请添加

Locale.setDefault(Locale.ENGLISH);

在构建您的验证器工厂之前。在您的示例中可能看起来像这样:

private static Validator validator;

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