SqLite in-memory testing for Fluent NHibernate

I love Fluent NHibernate, it’s so readable and clean. But I found getting it configured (using the new Fluently.Configure() method) to play nicely in integration tests against SqLite in-memory database a bit of a challenge. The problem was working out how SqLite in-memory databases behave (they are destroyed when the connection is closed), and how to export the schema into the in-memory database. For the latter I’m grateful to Daniel Hölbling for his post describing how to do the latter using Fluent. Here’s the finished code:

public class NHibernateTestFixtureBase
{
    protected ISessionFactory SessionFactory { get; set; }
    protected Configuration SavedConfig { get; set; }

    public void SetUp()
    {
        FluentConfiguration configuration = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.InMemory())
            .Mappings(m =>
                m.FluentMappings
                .AddFromAssembly(
                    Assembly.Load("Assembly.With.Mappings")))
            .ExposeConfiguration(cfg =>
            {
                 cfg.AddProperties(new Dictionary
                 {{"proxyfactory.factory_class",
               "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"
                 }});
                 SavedConfig = cfg;
             });

        SessionFactory = configuration.BuildSessionFactory();
    }

    public ISession CreateSession()
    {
        ISession session = SessionFactory.OpenSession();
        var export = new SchemaExport(SavedConfig);
        export.Execute(true, true, false, session.Connection, null);
        return session;
    }
}

posted 2 years ago