I am coding a simple web application that uses Hibernate.
I would like to implement the following use case. The user tries to delete an entity, but this entity is being referenced by another one. So the user is presented with a message that explains that the entity cannot be deleted because it is being used by another one, and that the other entity should be deleted first.
I therefore would like to have a unit test against the Dao, that will ensure a constraint violation exception is thrown following a use case in which the user attempts to delete an entity referenced by another one.
I have several questions.
Question 1
----------
Is this unit test a good idea ?
Question 2
----------
How to "recover" from the exception, be it a checked application exception, or a Spring DataAccessException, or an HibernateException ?
That is, how to make use of the dao object after the catching of the exception ? And how to handle the entity object ?
I was told that the transaction should be rolled back, the session should be closed, and the entity object should be re-attached to a new session. This is a lot of action, and I have no idea how to implement it.
Thanks for any guidance on this.Code:@Test public void testDelete() { contactReferer0 = contactRefererDao.makePersistent(contactReferer0); contactReferer1 = contactRefererDao.makePersistent(contactReferer1); long count = contactRefererDao.countAllRows(); assertEquals(2, count); contactRefererDao.makeTransient(contactReferer0); count = contactRefererDao.countAllRows(); assertEquals(1, count); Contact contact = new Contact(); contact.setEmail("email"); contact.setMessage("message"); DateTime contactDateTime = new DateTime(); contact.setContactDateTime(contactDateTime); contact.setContactReferer(contactReferer1); contact = contactDao.makePersistent(contact); try { contactRefererDao.makeTransient(contactReferer1); fail(); // Assertion error !!! <<================================ } catch (HibernateException e) { } count = contactRefererDao.countAllRows(); assertEquals(1, count); contact.setContactReferer(null); contactRefererDao.makeTransient(contactReferer1); count = contactRefererDao.countAllRows(); assertEquals(0, count); }


Reply With Quote
