Reputation: 393
I wrote a test, that should test the validations of my class CasinoDto, but they are not working, the assertion fails. The import should be correct, maybe i wrote a wrong test but i dont know where the error is.
CasinoDto class:
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
public class CasinoDto {
@Id
private Long casinoId;
@Size(min = 10, max=100000)
private Float sales;
private String country;
private String place;
@NotNull
private String street;
@NotNull
private String houseNumber;
}
The test which is not working:
private CasinoDto casinoDto;
private static Validator validator;
private static ValidatorFactory validatorFactory;
@BeforeAll
public static void createValidator(){
validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@BeforeEach
void setCasinoDto(){
casinoDto = CasinoDto.builder()
.casinoId(1L)
.country("yes")
.houseNumber("12")
.place("mareo")
.sales(20000f)
.street("irgendwo")
.build();
}
@AfterEach
void testViolation(){
Set<ConstraintViolation<CasinoDto>> violations = validator.validate(casinoDto);
Assertions.assertFalse(violations.isEmpty());
}
@Test
void testNotNull(){
casinoDto.setStreet(null);
}
I already checked the dependencies and they should be right.
Upvotes: 1
Views: 501
Reputation: 6391
There is a problem with the field sales
- you cannot use @Size
with number types. According to the docs:
Supported types are:
CharSequence (length of character sequence is evaluated)
Collection (collection size is evaluated)
Map (map size is evaluated)
Array (array length is evaluated)
In your case (with Float) you need to use a different set of annotations:
@NotNull
@DecimalMax("100000")
@DecimalMin("10")
private Float sales;
Notice that I also placed @NotNull
because @DecimalMin
and @DecimalMax
consider nullable elements as valid (it's the common approach of Bean Validation API).
All annotations are from the package javax.validation.constraints
.
Upvotes: 2