我创建了一个验证器来验证我在模型类(即@NotNull@Pattern等)中定义的注释。在编写测试用例时,我创建了以下断言,用于查找一个违规情况。但是,在某些情况下,违反次数超过1次。如何修改以下内容以检查多个违规?我本质上想要一个像

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测试

07-27 13:29