Archive for May, 2008|Monthly archive page

Unit testing Castle Active Record using SQLite in-memory database

Sorry about the formatting and everything else but here is how I enabled SQLite in-memory mode for database hitting unit tests in Visual Studio. The approach is not ideal but it works with TestDriven.net.

The software

Download the Finisar SQLite provider. Copy the files SQLite.NET.dll and SQLite3.dll into your test project root. Add a reference to SQLite.NET.dll. Change the properties of SQLite3.dll from “Allways copy” to “If newer”.

Custom connection provider

The SQLite in-memory destroys all the data in the database when the connection is closed. By default, when using Castle Active Record the connection are closed after every operation like CreateSchema(). There can be some property setting to use the same connection for all the operations between a test setup and tear down, but it was quite easy to write a custom connector that does the same thing. Here is the code.

public class SQLiteInMemoryTestingConnectionProvider : NHibernate.Connection.DriverConnectionProvider
{
public static System.Data.IDbConnection Connection = null;

public override System.Data.IDbConnection GetConnection()
{
if (Connection == null)
Connection = base.GetConnection();

return Connection;
}

public override void CloseConnection(System.Data.IDbConnection conn) { }
}

Configuring the Active Record

Set the following properties for Active Record initialization:

hibernate.connection.driver_class = NHibernate.Driver.SQLiteDriver

hibernate.dialect = NHibernate.Dialect.SQLiteDialect

hibernate.connection.provider = MyNamespace.SQLiteInMemoryTestingConnectionProvider, MyAssemblyNameContainingTheProvider

hibernate.query.substitutions = true=1;false=0

hibernate.connection.connection_string = Data Source=:memory:;Version=3;New=True;

Closing the connection after each test

In your test tear down method, close the connection manually:

if (SQLiteInMemoryTestingConnectionProvider .Connection != null) SQLiteInMemoryTestingConnectionProvider .Connection.Close();

SQLiteInMemoryTestingConnectionProvider .Connection = null;

This causes the data created by the test to be destroyed. Use test setup to recreate the database schema for the following test.