如何检查多个约束违规?

huangapple go评论87阅读模式
英文:

How can I check for more than one constraint violation?

问题

我已创建一个验证器来验证我在模型类中定义的注释,例如 @NotNull@Pattern 等。在编写测试用例时,我创建了以下断言,该断言查找一个违规情况。然而,在某些情况下可能会有多个违规情况。我该如何修改以下代码以检查多个违规情况?我实际上希望有一个类似于以下的断言:

result.getViolations().size(), is(1 或更多)

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();

Set<ConstraintViolation<CreateRequest>> violations = validator.validate(createRequest);

if (violations.isEmpty()) {
    CreateResponse createResponse = restTemplate.postForObject(clientProperties.getCreateUrl(), createRequest, CreateResponse.class);
    return new ClientResult<>(createResponse);
} else {
    return new ClientResult<>(violations);
}

assertThat("违规数量", result.getViolations().size(), is(1));

注意:由于您要求只返回翻译后的部分,我已删除了不属于翻译内容的部分。如果您需要进一步的帮助,请随时提问。

英文:

I have created a validator to validate the annotations I have defined in my model class ie @NotNull, @Pattern etc. Whilst writing my test cases, I created the below assertion which looks for one violation. However in some cases there is more than 1 violation. How do I amend the below to check for more than one violation? I essentially want to have an assertion like

result.getViolations().size(), is(1 or more)

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    Validator validator = validatorFactory.getValidator();

    Set&lt;ConstraintViolation&lt;CreateRequest&gt;&gt; violations = validator.validate(createRequest);

    if (violations.isEmpty()) {
        CreateResponse createResponse = restTemplate.postForObject(clientProperties.getCreateUrl(), createRequest, CreateResponse.class);
        return new ClientResult&lt;&gt;(createResponse);
    } else {
        return new ClientResult&lt;&gt;(violations);
    }

        assertThat(&quot;Number of violations&quot;, result.getViolations().size(), is(1));

答案1

得分: 1

你可以将最后一行修改为:

assertThat("违规数量", result.getViolations().size(), is(oneOf(1, 2)));

有关oneOf方法,请参阅文档

已使用Hamcrest 2.2进行测试。

英文:

You can change the last line to:

assertThat(&quot;Number of violations&quot;, result.getViolations().size(), is(oneOf(1, 2)));

See docs for oneOf method.

Tested with Hamcrest 2.2

huangapple
  • 本文由 发表于 2020年3月4日 05:58:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/60516131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定