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 15:26 by DanWatson

Comments

October 9. 2009 09:40

trackback

SQLite Nunit & Fluent Nhibernate - Test your data access layer

DotNetBurner - burning hot .NET content

DotNetBurner - NHibernate

October 9. 2009 09:56

Jon Kruger

Awesome stuff... thanks for the post.

Jon Kruger

October 31. 2009 03:02

Latex Mattress

great tips - the pictures help out

Latex Mattress

November 22. 2009 10: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

January 30. 2010 22:33

Free Club Penguin

This code helped me greatly.

Free Club Penguin

January 31. 2010 14:54

sms web service

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

sms web service

January 31. 2010 14:54

full tilt

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

full tilt

February 3. 2010 22:12

learn poker

Great post, I look forward to reading more.

learn poker

February 7. 2010 03:16

best home based business

Very useful info. Hope to see more posts soon!

best home based business

February 9. 2010 18: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 11. 2010 08: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 18. 2010 18:16

business opportunities from home

Awesome post! Interesting info to know.

business opportunities from home

February 24. 2010 03:13

Budget Van Lines Reviews

nice code..pretty easy to follow

Budget Van Lines Reviews

February 26. 2010 19:14

Fred Perry

Your site is really helping my asp

Fred Perry

March 14. 2010 13:28

Spa types

Thanks for such a nice blog post....i was searching for something like that.
Thanks for posting this informative article....

Spa types

March 27. 2010 11:08

Keylogger Software

nice post here,thanks for share!thanks again!

Keylogger Software

April 7. 2010 22:06

Certified Loose Diamonds

Excellent article.Its really a good article. SQLite Nunit & Fluent Nhibernate  gives me lots of pleasure and interest. It’s a most important post. So i want to know some other details about this article. Thanks

Certified Loose Diamonds

April 10. 2010 12:07

zz

<FONT size=3><SPAN lang=EN-US style="FONT-SIZE: 8.5pt; COLOR: #333333; FONT-FAMILY: Arial"><SPAN lang=EN-US><FONT face=宋体 color=#000000><SPAN lang=EN-US style="COLOR: #333333; FONT-FAMILY: Arial; mso-bidi-font-size: 10.5pt"><?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p>
<P><FONT face=宋体><FONT color=#000000><SPAN lang=EN-US style="FONT-SIZE: 10.5pt">If </SPAN><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-family: Arial">you’re looking for <A title=shoesonline href="www.jordanmvp.com/"><B><FONT color=#000000>shoesonline</FONT></B></A>,wecan provide for numerous models, different colors,and high quality materials -All these may be said about the popular </SPAN><SPAN lang=EN-US style="FONT-SIZE: 10.5pt"><A title="Air Jordan shoes" href="www.jordan56.com/"><STRONG><SPAN style="COLOR: windowtext; FONT-FAMILY: 宋体; TEXT-DECORATION: none; text-underline: none; mso-bidi-font-family: Arial">Air Jordan shoes</SPAN></STRONG></A></SPAN></FONT><FONT color=#000000><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-family: Arial">. Just <A title="the shoes" href="ny.xmu.edu.cn/shoesonline"><B>the shoes</B></A>which changed the world! These model appeared during Jordan's first return to basketball in 1995. It was such an occasion and the designers tried to create a new model as quickly as possible. So was the quality of these <A title="Air Jordan shoes" href="www.jordanmvp.com/"><STRONG>Air Jordan shoes</STRONG></A><STRONG>.</STRONG></SPAN><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-size: 12.0pt; mso-bidi-font-family: Arial">Nowadays there are so many fakes of </SPAN><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-size: 12.0pt"><A title="cheap Air Jordan shoes" href="http://www.jordan56.com/"><SPAN" rel="nofollow">http://www.jordan56.com/"><SPAN style="COLOR: windowtext; TEXT-DECORATION: none; mso-bidi-font-size: 10.5pt; text-underline: none; mso-bidi-font-family: Arial">Air </SPAN></A></SPAN><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-size: 12.0pt; mso-bidi-font-family: Arial"><A title="Jordan shoes" href="ny.xmu.edu.cn/JordenShoes"><STRONG>Jordan shoes</STRONG></A>. <SPAN style="mso-spacerun: yes">&nbsp;</SPAN>The genuine </SPAN><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-size: 12.0pt"><A title="Michael Jordan shoes" href="http://www.jordan56.com/"><SPAN" rel="nofollow">http://www.jordan56.com/"><SPAN style="COLOR: windowtext; TEXT-DECORATION: none; mso-bidi-font-size: 10.5pt; text-underline: none; mso-bidi-font-family: Arial">Michael Jordan shoes</SPAN></A></SPAN><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-size: 12.0pt; mso-bidi-font-family: Arial"> are very comfortable and you even will be eager to walk home in them.</SPAN><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-size: 12.0pt"> Here at <A title=JordenShoes.com href="www.jordanmvp.com/.../A>&nbsp;we take security very seriously.If want to look for more comfortable shoes,please login the JordenShoes.com. We have a huge selection of<STRONG> </STRONG><A title=JordenShoes href="www.jordanmvp.com/.../FONT><SPAN lang=EN-US style="FONT-SIZE: 10.5pt; mso-bidi-font-family: Arial"><o:p></o:p></SPAN></P></o:p></SPAN></FONT></SPAN></SPAN></FONT

zz

April 11. 2010 02:39

Hobo Bags

Just wanna say thank you for the data that you simply have been sharing. Just found your site and genuinely appreciate what you're doing.

Hobo Bags

April 12. 2010 00:04

Easy Photo Print - How to Print and Save Photos

Thanks for your nice article.I visit this site some other times.Its really found good information about Thanks for your nice article.I visit this site some other times.Its really good.Thanks for sharing.


Easy Photo Print - How to Print and Save Photos

April 12. 2010 18:36

Cyclone Weather

Thanks for taking the time to converse about  this, I feel  fervently  about this and I enjoy learning about this topic. I have found it really useful. keep up great job..

Cyclone Weather

April 13. 2010 13:20

shooting games

Gorgeous blogpost!!!

shooting games

April 14. 2010 15:16

Coaster bedroom furniture

There are certainly a lot more details to take into consideration,

but thanks for sharing this post

Coaster bedroom furniture

April 15. 2010 06:09

Dentist St Petersburg

Post is nicely written about SQLite Nunit and Fluent Nhibernate and it contains many good things for me. I am glad to find your impressive way of writing the post. Now it become easy for me to understand and implement the concept. Coding is very helpful. Thanks for sharing the post.

Dentist St Petersburg

April 17. 2010 13:05

obgyn clearwater

Wow that is alot to take in in one sitting. will bookmark and come back to for future referance.

obgyn clearwater

April 18. 2010 06:42

how to make money online

I am very enjoyed for this side. Its a nice topic. SQLite Nunit & Fluent Nhibernate  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.

how to make money online

Comments are closed