英文:
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<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("Number of violations", 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("Number of violations", result.getViolations().size(), is(oneOf(1, 2)));
See docs for oneOf
method.
Tested with Hamcrest 2.2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论