Search code examples
javaspring-bootresttemplatejunit5hamcrest

How can I check for more than one constraint violation?


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

Solution

  • 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