Last month I wrote a post explaining how to test your data access layer by using Fluent NHibernate to generate an in-memory SQLite database from an applications domain model and fluent mappings. You can then run unit tests against the SQLite database rather than mocking objects.
Over the last couple of weeks I have become less fond of Fluent NHibernate (long story! Curse & Swear!) and wanted to recreate the same functionality using NHibernates standard mappings and features. So without further adieu…..
Firstly you will need to build up the schema for the SQLite database. This is created automatically based upon the applications domain model and mapping files.
public abstract class InMemoryDatabase : IDisposable
{
private static Configuration _configuration;
protected static ISessionFactory _sessionFactory;
protected static ISession _session;
protected InMemoryDatabase()
{
_sessionFactory = CreateSessionFactory();
_session = _sessionFactory.OpenSession();
BuildSchema(_session);
}
private static ISessionFactory CreateSessionFactory()
{
//NHibernateProfiler.Initialize();
Dictionary<string, string> properties = new Dictionary<string, string>
{
{"connection.driver_class","NHibernate.Driver.SQLite20Driver"},
{"dialect", "NHibernate.Dialect.SQLiteDialect"},
{"connection.provider","NHibernate.Connection.DriverConnectionProvider"},
{"query.substitutions", "true=1;false=0"},
//{"show_sql", "true"},
{"connection.connection_string","Data Source=MyTestDb.db;Version=3;New=True;"},
{"proxyfactory.factory_class","NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"},
{"cache.provider_class", "NHibernate.Cache.HashtableCacheProvider"},
{"cache.use_second_level_cache", "true"},
{"cache.use_query_cache", "true"}
};
_configuration = new Configuration()
.SetProperties(properties)
.AddAssembly(typeof(Person).Assembly);
return _configuration.BuildSessionFactory();
}
private static void BuildSchema(ISession session)
{
SchemaExport export = new SchemaExport(_configuration);
export.Execute(true, true, false, session.Connection, null);
}
public void Dispose()
{
_sessionFactory.Dispose();
}
}
You will then need to create a class that derives from InMemoryDatabase, this is where the static data is setup. When calling Session.Flush() the data is persisted to the SQLite database.
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();
}
}
As long as your unit test classes then derive from InMemoryData you will have access to the ISession object that is associated to the SQLite database and will be able to execute unit tests against the static data.
I usually create a base class that all my data access tests derive from. I setup my data access repository’s to accept an ISession object via a constructor argument (this is also really useful for dependency injection which is outside the scope of this post) and in this instance pass in the ISession object associated with the SQLite database.
[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();
}
}
Here is an example of a unit test class. The class is derived from TestBase which then allows my data tests to make assertions on the data access methods but with those methods executing against the SQLite database and static data.
public class PersonDataTest : TestBase
{
[Test]
public void Select_All_People_Should_Return_3()
{
Assert.AreEqual(3, PersonData.SelectAllPeople().Count());
}
}
As always here’s the code for you to
download.
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());
}
}
}
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.
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).