SQLite Nunit & Fluent Nhibernate - Test your data access layer

Download Code

I think that the worst part of unit testing is that it’s never straight forward to test an applications data access. I always feel worried about just creating in memory collections or objects to test against or mocking data access components. I have found on occasion when the code is switched over from test data to work against an RDBMS issues can occur. What I really want is an in memory database that is created with test data and then disposed of once the tests have been carried out.

Below is a class which will generate an in memory SQLite database based on the model and Nhibernate fluent mappings created (if you don't know how to create the mappings and model then read here). The important line of code here is on line 18 which looks in the assembly where the fluent mappings are located so the framework is able to generate the database schema.

using System;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using Nhibernate.Blog.Data.Helpers;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Nhibernate.Blog.Test.DatabaseSetup
{
    public abstract class InMemoryDatabase : IDisposable
    {
        private static Configuration _configuration;
        private static ISessionFactory _sessionFactory;

        protected ISession Session { get; set; }

        protected InMemoryDatabase()
        {
            _sessionFactory = CreateSessionFactory();
            Session = _sessionFactory.OpenSession();
            BuildSchema(Session);
        }
        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
                .Mappings(M => M.FluentMappings.AddFromAssemblyOf<SessionFactory>())
                .ExposeConfiguration(Cfg => _configuration = Cfg)
                .BuildSessionFactory();
        }
        private static void BuildSchema(ISession Session)
        {
            SchemaExport export = new SchemaExport(_configuration);
            export.Execute(true, true, false, Session.Connection, null);

        }

        public void Dispose()
        {
            Session.Dispose();
        }
    }
}

Now you will have an ISession object which you can add test data to. The InMemoryData class inherits from the InMemoryDatabase class so it has the ISession available to it. By calling Session.Save(object); and then Session.Flush(); the Entity will be added to the SQLite database.

using Nhibernate.Blog.Model;

namespace Nhibernate.Blog.Test.DatabaseSetup
{
    public abstract class InMemoryData : InMemoryDatabase
    {
        protected InMemoryData()
        {
            Account AccountOne = new Account(1, "AC001");
            Account AccountTwo = new Account(2, "AC002");

            Session.Save(AccountOne);
            Session.Save(AccountTwo);

            Session.Flush();
            
            Session.Save(new Person(1, "Dan", "Watson", AccountOne));
            Session.Save(new Person(1, "James", "May", AccountTwo));
            Session.Save(new Person(1, "Andrew", "Plum", AccountOne));
            
            Session.Flush();
        }
    }
}

Using Nunit (or your test framework of choice) create a base class that inherits from the InMemoryData class so all the data tests have access to the Nhibernate Session. I created data repository classes which have overloaded constructors which accept an ISession object. Now you will be able to run methods in the data access layer against the in memory SQLite database.

using Nhibernate.Blog.Data.Interfaces.Repository;
using Nhibernate.Blog.Test.DatabaseSetup;
using NUnit.Framework;
using Nhibernate.Blog.Data.Repository;

namespace Nhibernate.Blog.Test.Base
{
    [TestFixture]
    public abstract class TestBase : InMemoryData
    {
        protected IPersonData PersonData { get; set; }
        protected IAccountData AccountData { get; set; }

        [SetUp]
        public void Init()
        {
            PersonData = new PersonData(Session);
            AccountData = new AccountData(Session);
        }

        [TestFixtureTearDown]
        public void Die()
        {
            Dispose();
        }

    }
}

You can now call the methods in your data access classes and make assertions based on the test data added to the SQLite database. Just remember to inherit from you test base class which set’s up the in memory database, data and data access classes.

using System.Linq;
using Nhibernate.Blog.Test.Base;
using NUnit.Framework;

namespace Nhibernate.Blog.Test.DataTests
{
    public class PersonDataTest : TestBase
    {
        [Test]
        public void Select_All_People_Should_Return_3()
        {
            Assert.AreEqual(3, PersonData.SelectAllPeople().Count());
        }
    }
}

Unit testing

An added bonus to this method of data access testing is you are able to see the SQL statements generated for both the schema and also each unit test run which makes it much easier to debug issues when developing the code.
image

Although there are a few levels of inheritance once it is setup its really easy to maintain and makes unit testing easy to carry out.  You can download the sample code from here (you will need VS2008 Standard / Pro / Team to run this or if your über cool use VS2010 beta).

Twitter Twitter Twitter Twitter Twitter
October 20, 2009 10:26 by DanWatson

Comments

October 13. 2009 18:38

trackback

SQLite Nunit & Fluent Nhibernate - Test your data access layer

Thank you for submitting this cool story - Trackback from DotNetShoutout

DotNetShoutout

October 13. 2009 18:40

trackback

SQLite Nunit & Fluent Nhibernate - Test your data access layer

DotNetBurner - burning hot .NET content

DotNetBurner - NHibernate

October 13. 2009 18:56

Jon Kruger

Awesome stuff... thanks for the post.

Jon Kruger

November 4. 2009 12:02

Latex Mattress

great tips - the pictures help out

Latex Mattress

November 5. 2009 03:40

vitamin c

You described this article very beautifully with pictures too. So every one can easily understand it. Keep posting such a way as I can keep visiting this blog very often. Thanks for this great post.

vitamin c

November 23. 2009 09:12

Our simply

great tips - the pictures help out

Our simply

November 26. 2009 19:01

short jokes

data access layer is an good technical post which need to understand and good results comes up after use. thanks !!!

short jokes

November 28. 2009 14:16

life jackets

The article is really interesting. Even the Example given in the article shows how we can do access the Data layer.

life jackets

December 25. 2009 06:28

homeowner loans

some interesting style there but i guess content is more important. nice one

homeowner loans

January 16. 2010 16:50

Wiring Diagram

Thank you for sharing, interested story.

Wiring Diagram

February 4. 2010 07:33

Free Club Penguin

This code helped me greatly.

Free Club Penguin

February 4. 2010 17:01

cheap printer ink

Hi,
Interesting read, thanks for helping keep me busy at work ;)

cheap printer ink

February 4. 2010 23:54

sms web service

Useful info. Hope to see more good posts in the future.

sms web service

February 4. 2010 23:54

full tilt

Nice job, it’s a great post. The info is good to know!

full tilt

February 8. 2010 07:12

learn poker

Great post, I look forward to reading more.

learn poker

February 11. 2010 11:22

loans for unemployed people

very nice writing, I can appreciate that because it is worth for it

loans for unemployed people

February 11. 2010 12:16

best home based business

Very useful info. Hope to see more posts soon!

best home based business

February 14. 2010 03:11

Chris

This code example was exactly the starting point I was looking for.  Thank you for taking the time to post this.

Chris

February 15. 2010 17:20

promozioni dei casinò di Internet

I've been looking at D6 schema a the schema module and very interested in the idea of providing automated node scaffolding for custom node types. The idea is that a single module can provide the db scaffolding for node insert, update, delete, delete revision, etc. by simply inspecting the node's schema. As a test I added this code to schema module - its not complete 

promozioni dei casinò di Internet

February 22. 2010 18:28

Terme Di Saturnia

I think, it’s a helpful topic. I like this topic. I want know some helpful things from this side. It fresh my mind and experience. So lots of thanks for sharing this information with me.

Terme Di Saturnia

February 23. 2010 03:16

business opportunities from home

Awesome post! Interesting info to know.

business opportunities from home

February 23. 2010 13:21

Quick Loans

A really nice site you have here.

Quick Loans

February 24. 2010 16:59

forex vps

I like this topic. I want know some helpful things from this side. It fresh my mind and experience. So lots of thanks for sharing this information with me.

forex vps

February 27. 2010 22:09

dentists

I am happy to visit your site.Thanks for your site.I want more information.

dentists

February 28. 2010 12:13

Budget Van Lines Reviews

nice code..pretty easy to follow

Budget Van Lines Reviews

March 1. 2010 05:09

Customer insights

Its a really nice article.I got it.Thanks for your nice article.

Customer insights

March 1. 2010 22:39

Youngblood cosmetic

I visit this site. It gives me lots of pleasure and interest. It’s a most important post.

Youngblood cosmetic

March 2. 2010 20:44

ucvhost

I am very enjoyed for this side. Its a nice topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. I think it may be help all of you. Thanks.

ucvhost

March 3. 2010 04:14

Fred Perry

Your site is really helping my asp

Fred Perry

March 3. 2010 17:40

Matis cosmatics

Its a very useful article. We will be acquire lot of things from this site.So i want some information about this post.

Matis cosmatics

March 4. 2010 05:13

Online Poker

Hi,




It’s hard to find knowledgeable people on this topic, but you sound like you know what you’re talking about! Thanks


Online Poker

March 4. 2010 19:03

Youngblood cosmetic

Hello everyone, please quickly visit this site and know about this great post. It is really a good post. I like this.

Youngblood cosmetic

March 11. 2010 14:08

Convert PDF to image

Resources like the one you mentioned here will be very useful for me!

Convert PDF to image

March 13. 2010 15:19

mod converter

I happy to find many good point here,

mod converter

March 13. 2010 15:28

range hood

thank you for the post.
We see more kitchen hoods here.  

range hood

Add comment



(Will show your Gravatar icon)



 
Are you human? number6 + number4 =