如何检查多个约束违规?

How can I check for more than one constraint violation?

我创建了一个验证器来验证我在模型 class 中定义的注释,即 @NotNull@Pattern 等。在编写测试用例时,我创建了以下断言寻找一次违规行为。但是,在某些情况下,违规行为不止一次。我如何修改以下内容以检查是否存在多个违规行为?我本质上想要一个像

这样的断言

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));

您可以将最后一行更改为:

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

oneOf 方法参见 docs

使用 Hamcrest 2.2 测试