Testing with NHibernate and SQLite

Disclaimer: I’m quite new to NHibernate. I’m just learning it, so do not assume that what I’m presenting here is a good idea, or that I know what I’m doing. You have been warned.

There does not seem to be too much details on how to set up a test environment for NHibernate testing using SQLite. Ayende has a nice post on this, but he does not go into details of how, what and where, so I decided to fill in the blanks, and provide an up to date sample for NHibernate 2.1.

Let’s first gather all the things we need:

Now we need to add references to all these projects. Make sure you add correct reference to System.Data.SQLite (either x86 version from the main directory, or x64 version from x64 folder if you’re running on 64bits).

You also can’t add reference to sqlite3.dll, because it’s an unmanaged dll. I simply add it as element to solution and set it to copy to output directory. After all, your solution should look roughly like this:


I also have a base class for my tests that does all the setup for me. Here’s how it looks like:

public abstract class DbTestsBase<T>
    protected ISessionFactory factory;
    protected T sut;
    private string dbFile;
    public void Init(params Assembly[] assembliesWithMappings)
        dbFile = GetDbFileName();
        var configuration = new Configuration()
            .AddProperties(new Dictionary<string, string>
                                   { Environment.ConnectionDriver, typeof( SQLite20Driver ).FullName },
                                   { Environment.Dialect, typeof( SQLiteDialect ).FullName },
                                   { Environment.ConnectionProvider, typeof( DriverConnectionProvider ).FullName },
                                   { Environment.ConnectionString, string.Format( "Data Source={0};Version=3;New=True;", dbFile) },
                                   { Environment.ProxyFactoryFactoryClass, typeof( ProxyFactoryFactory ).AssemblyQualifiedName },
                                   { Environment.Hbm2ddlAuto, "create" },
                                   { Environment.ShowSql, true.ToString() }
        foreach (var assembly in assembliesWithMappings)
        new Remapper().Remap(configuration);
        factory = configuration.BuildSessionFactory();
    public void TearDownTests()
    private string GetDbFileName()
        var path = Path.GetFullPath(Path.GetRandomFileName() + ".Test.db");
        if (!File.Exists(path))
            return path;
        // let's try again
        return GetDbFileName();
    private void EnsureDbFileNotExists()
        if (File.Exists(dbFile))

There are couple interesting points in this code:

I expose the SessionFactory, not Session. That’s because I use this class for testing repositories in stateful application, that manage the session themselves.

I save the database to file, instead of keeping it in memory like Ayende does. That’s connected to the previous fact. Apparently, in-memory database only lives as long as session that created it, which does not cut it for me.

I then use the class like this:

class Entity1Tests : DbTestsBase<Entity1>
    public void SetUp()
    public void Member_should_action()
        //some code

Pretty simple and so far, covers my needs.

Posted 08-14-2009 12:03 AM by Krzysztof Koźmic
Filed under:



Daniel Hölbling wrote re: Testing with NHibernate and SQLite
on 08-13-2009 6:41 PM

If your repositories don't change sessions going against a in-memory db is quite simple. I solved the problem with BuildSchema running on it's own session by exposing the configuration:


greetings Daniel

Thomas Weller wrote re: Testing with NHibernate and SQLite
on 08-14-2009 3:34 AM

I also like the idea of unit testing against an in-memory database. It's fast and lightweight.

Unfortunately, SQLite does not support  constraints like e.g. foreign keys.

So, while the idea itself is attracting, this methodology is of very limited use in real-life projects.

DotNetShoutout wrote Testing with NHibernate and SQLite - Krzysztof Kozmic - Devlicio.us
on 08-14-2009 3:07 PM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Sanjeev Agarwal wrote Daily tech links for .net and related technologies - August 12-17, 2009
on 08-16-2009 6:34 AM

Daily tech links for .net and related technologies - August 12-17, 2009 Web Development How to use Ninject

NHibernate blog wrote How-To: Using the N* Stack, part 4
on 08-16-2009 7:45 PM

This is part 4 of my series on ASP.NET MVC and NHibernate. If you’re not up to date, you can go check

Colin Jack wrote re: Testing with NHibernate and SQLite
on 09-13-2009 1:42 PM

You might want to re-run your tests against SQL Server just to check it really is worth the effort, we found the time saving wasn't massive (and we had issues when trying to run our code against SQLite in-memory) so just went back to running against SQL Server.

it-crow wrote re: Testing with NHibernate and SQLite
on 03-17-2010 3:44 AM

thanks for this post. helped a lot.

EdgarT wrote re: Testing with NHibernate and SQLite
on 03-20-2010 3:36 PM


SQLite already support foreign keys.

check it:


Blog J.Schweiss wrote Testing with NHibernate and SQLite
on 01-29-2011 2:19 AM

Testing with NHibernate and SQLite

srad wrote re: Testing with NHibernate and SQLite
on 06-03-2011 6:43 PM
Jakub Linhart wrote re: Testing with NHibernate and SQLite
on 01-07-2012 5:29 AM

Execution of such test suit is most likely very slow. To achieve blazingly fast execution, database can be kept in memory taking advantage of connection pooling and sqlite backup api.


123 wrote re: Testing with NHibernate and SQLite
on 06-25-2012 1:19 PM


About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)