Unittesting and NHibernate: does it work?

If you want to keep developers working on the unittest-code than it is best to have those tests run fast
as is explained on Michael Feathers blog.

The best way of having your tests run fast is by not having your objects that you want to test to touch the database. Because database access is slow.

But as Colin Jack points out, if you have been working with
NHibernate there are some gotchas when your code also wants to remove stuff from the database at some point. And I am sure every codebase does want to do that at some point :vork:

In our team, we found the following solution to this problem to make our code still running in non-database connected tests..

As all of our NHibernate persistent objects have a key in the database which is non-zero, and all our NHibernate persistent objects inherit from our base class BusinessObject that has a unique Id that identifies the object per table, we harnassed our code to be used in a non-database unittest as follows:

Pseudo-code


DeleteRecordFromList(Item item, IList<Item> nhList)
{
if (nhList.Contains(item))
{
// is this object a persisted object?
// All of our objects have the unique-key
// in the .Id field so if that is zero
// the object is only existent in memory.
if (item.Id != 0)
{
// Delete it from database
OurContext.NHSession.Delete(item);
}
}
}

Of course this is a very dirty way of checking if objects were persisted or not, but at least this code can still be used in a non-database using unittest.