Reputation: 5232
I am trying to test Spring Data Repository, particularly to test that exception would be thrown upon passing Entity with the wrong parameters. Entity is annotated with Java Bean Validation annotations @NotNull
and @Email
@SpringBootTest(classes = PatientPKServiceApplication.class)
@RunWith(SpringRunner.class)
@DataJpaTest
public class PatientPKRepositoryTest {
@Autowired
private PatientPKRepository repository;
@Rule
public ExpectedException thrownException = ExpectedException.none();
@Test
public void newEntityWithInvalidParametersShouldThrownConstraintViolations() throws Exception {
this.thrownException.expect(ConstraintViolationException.class);
this.repository.save(new PatientPK(null, null, null));
}
Repository is
public interface PatientPkRepository extends JpaRepository<PatientPk, Long> {
}
Test fails,
java.lang.AssertionError: Expected test to throw an instance of javax.validation.ConstraintViolationException
at org.junit.Assert.fail(Assert.java:88)
at org.junit.rules.ExpectedException.failDueToMissingException(ExpectedException.java:263)
at org.junit.rules.ExpectedException.access$200(ExpectedException.java:106)
what is the best way to test this behavior? I don't want to validate manually.
Update SOLUTION : As suggested by JB Nizet (see answer below) we need to ensure that Persistence Context is actually flushed. Changing repository.save
to repository.saveAndFlush()
worked out.
Upvotes: 1
Views: 343
Reputation: 691805
The documentation says:
By default, data JPA tests are transactional and roll back at the end of each test.
So since your test is transactional, and since it rollbacks, and since you never flush anywhere, the save() operation never actually tries to write to the database, and the validation constraints, executed before flush, are never validated.
Upvotes: 2