Reputation:
Method countryDao.delete(countryEntity) should throw ConstraintViolationException and the test should pass only if the exception is thrown.
However, the test in the form hereunder does not pass and I get message "java.lang.AssertionError: Expected test to throw an instance of org.hibernate.exception.ConstraintViolationException"
@Test
public void testDeleteWithCities() throws Exception {
exception.expect(ConstraintViolationException.class);
CountryEntity countryEntity = countryDao.find(1L);
countryDao.delete(countryEntity);
}
After I add the last line to the test, it does pass:
@Test
public void testDeleteWithCities() throws Exception {
exception.expect(ConstraintViolationException.class);
CountryEntity countryEntity = countryDao.find(1L);
countryDao.delete(countryEntity);
Assert.assertEquals(3, countryDao.findAll().size());
}
Should it behave like this? I beleive that the Assert.assertEquals(3, countryDao.findAll().size());
should not be needed.
Thanks for any help.
Upvotes: 1
Views: 432
Reputation: 692151
My guess is that your test is transactional. So the DAO.delete()
method is done in the transaction used for the test method.
delete()
or remove()
doesn't immediately deletes the entity, just like persist()
doesn't immediately inserts it. It simply marks the entity as deleted and, at the next flush, Hibernate will execute the delete query.
When calling findAll()
, you're implicitely flushing the Hibernate session (to make sure that findAll()
doesn't return the previously deleted entity). So the delete query is executed at this moment, and that causes the ConstraintViolationException
.
You can confirm that by turning on SQL logging, executing the code line by line, and examining the SQL queries generated at each step.
So, either don't make your test transactional, or call flush()
explicitely inside your test (which makes the intent clearer than calling findAll()
).
Upvotes: 1