I am currently writing some @SpringBootTest for bean validation in services.
@Data
@Document
public final class Supplier {
@Id
@NotEmpty
private String supplierId;
...
@NotEmpty
private String hash;
....
}
Test
Annotated with:
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
and
@Test
void testValidation() {
Supplier invalidSupplier = SupplierTestDataUtil.createSupplier("1234");
invalidSupplier.setSupplierId(null);
//works
assertThrows(ConstraintViolationException.class, () -> supplierService.publish(invalidSupplier));
//works
assertThrows(ConstraintViolationException.class, () -> supplierService.persist(invalidSupplier));
//works not
assertThrows(ConstraintViolationException.class, () -> supplierService.saveAndPublish(invalidSupplier));
//works
assertThrows(ConstraintViolationException.class, () -> supplierService.delete(invalidSupplier));
}
Service:
@Transactional
public Supplier saveAndPublish(@NotNull Supplier supplier) {
supplier.setHash(messageDigester.digest(supplier));
Supplier persisted = persist(supplier);
publish(supplier);
return persisted;
}
@Transactional
public Supplier persist(@Valid @NotNull Supplier supplier) {
return repository.save(supplier);
}
Supplier at saveAndFlush must not be valid at this point because required hash will be generated and set inside that method. Nevertheless my expectation was that ConstraintViolationException will be also thrown because I also call persist and publish method and pass that invalid document.
My point is that you can bypass BeanValidation within the same class.