Verifying you Data Access Layer when using NHibernate, Active Record, And Friends
I sometimes run into situations where people think that ORM is a magic word for no-work-required. This is especially true when they tend to realize that a few hours (on a small project, or a few hours here and there on a larger one) in front of an XML editor and some really simple classes, can more or less eliminate the need of a DAL.
It's tempting, I can write a functional DAL very quickly, but I also need to make sure that I test it. The problem is that you may be tempted to leave it like that, and that is where the danger lies. Let's imagine a very simple blog, where you've a many to one connection beteen posts and a blog, and you want to work with it. I can create the code for that in under ten minutes, in notepad, from memory alone (and no, it's not a boast, it's proof to how good the whole toolset is). But what then? Take a look at this code:
        Blog blog = new Blog("My"); 
        Blog.Posts.Add(new Post("noise")); 
        blog.Save();
        using(new SessionScope())//for lazy loading         
        {
          Blog fromDB = Blog.FindWithId(blog.Id);//verify save works
                
          //for each field, verify that the correct value was returned 
          //this is VERY important if you're going to play typing games, such as saving 
          //bool to tinyint columm, saving enums, etc...        
          Assert.AreEquals("My", fromDb.Name);
        
          bool isLoaded = NHibernateUtil.IsInitialized(fromDb.Posts);
          Assert.IsFalse(isLoaded);//verify lazy loading
                
          int count = fromDb.Posts.Count;// loads the lazy collection, also         
          Assert.AreEqual(1, count);// Verify that cascade works from blogs to poss
                
          Post postFromDb = Collection.First(fromDb.Posts);
          Assert.AreEquals("noise", postFromDb.Content);//verify that saving a post works        
        }    
This is one of the simplest possible tests, and check out how many failure point it has. You have to have this kind of coverage over all your entities (although I hate this word). If you don't, you can very easily get into a situation where the most minor change will break you code, and you'll not understand why this is happening.
 

Comments
Comment preview