INCLUDE_DATA

 
»
S
I
D
E
B
A
R
«
aquisto cialis levitra svizzera tadalafil bestellen viagra prix acheter du viagra acquista levitra cialis sur internet citrate de sildenafil compro viagra levitra ricetta kamagra pharmaceuticals cialis vente libre cialis suisse levitra italia vente de cialis viagra suisse kamagra gel viagra quanto costa cialis 20 mg prix cialis 10mg viagra verkauf cialis moins cher viagra prezzo levitra kopen acheter tadalafil acheter kamagra tadalafil generico impuissance sexuelle cialis preco levitra donna viagra 100 mg comprar cialis generico comprar levitra cialis a vendre procurer du cialis generische cialis vardenafil generico vardenafil generika levitra sur internet generische viagra acheter cialis generique acquista viagra achat cialis viagra 100 mg cialis generico kamagra en france viagra ordonnance acheter viagra achat vardenafil pastilla levitra viagra cialis differenze impotenza sessuale venta viagra medicament cialis curare impotenza kamagra te koop achat cialis 20mg levitra pharmacie cialis receta acquisto viagra net cialis en ligne achat de viagra cialis generique acheter acheter du cialis cialis 20 mg vardenafil 10 mg viagra alternativo citrate de sildenafil cialis sin receta viagra kopen acheter cialis en pharmacie kamagra bestellen comprar viagra pela internet viagra prescrizione levitra donne vente cialis venta de sildenafil achete levitra acheter cialis france venta de levitra viagra kosten cialis marche pas comprar vardenafil disfunzione erettile rimedi vardenafil generique viagra recensioni cialis generico prezzo viagra versand cialis europe viagra venta libre impotenza rimedi cialis rezeptfrei acheter kamagra france levitra ohne rezept acquisto viagra in contrassegno prix de cialis cialis prescrizione viagra acquisto online achat viagra pildoras cialis kamagra generique cialis prezzo cialis inde cialis sur le net acheter cialis en espagne levitra ordonnance viagra naturel cialis 10 mg acquistare levitra procurer du viagra acquisto viagra senza ricetta viagra controindicazioni levitra 20 mg compra viagra impuissance erection acheter cialis pharmacie prezzi levitra viagra ohne rezept kamagra apcalis comprar viagra commander du cialis cialis ricetta medica sildenafil 50 mg sildenafil venta viagra italia pilule levitra sildenafil generico viagra prijs
In Memory Database Testing with SQLite and NHibernate
Nov 11th, 2009 by Jason

A few weeks ago, I was faced with the challenge of testing how an application interacted with a database without mangling the data within it. What my company of employment had been doing prior was doing all database testing within a transaction and rolling back at the end. The issue with this approach was that behaviors like cascading wouldn’t occur, thus making the tests less than useful.

SQLite

Enter SQLite. SQLite is a basic, lightweight sql database wrapped into a single library. A benefit of its use is that SQLite can create an in-memory database that cleans up after all connections are closed. Its excellent for testing. Starting with a clean slate each test run can provide for consistent, reproducible results.

Prerequisites

NHibernate comes with support for SQLite from the NHibernate.Driver.SQLite20Driver class. However, you must provide two other files for it to work. First, sqlite3.dll, an unmanaged library of SQLite; include it in your test project and ensure “copy to output directory” is marked. Second, System.Data.SQLite, a managed library that allows ADO.NET to interact with SQLite; include this as a reference in your test project.

A Base Class

The following is a basic example of how to set up a base class for in memory database testing. Any tests that require database interaction should inherit from this class and will have the Session object available. Sessions last as long as each test fixture. Also, typeof(Plan) refers to the type of any of your domain classes.

 	public class InMemoryDatabaseTest
	{
		private static Configuration _configuration;
		private readonly object _baton = new object();
		private readonly ISessionFactory _sessionFactory;
		protected readonly ISession Session;

		public InMemoryDatabaseTest()
		{
			if (_configuration == null)
				lock (_baton)
					if (_configuration == null)
					{
						typeof(VersionDate2).GetField("_sqlType",BindingFlags.Static | BindingFlags.NonPublic).SetValue(null,new SqlType(DbType.DateTime));
						_configuration = new Configuration()
							.SetProperty(Environment.ReleaseConnections,"on_close")
							.SetProperty(Environment.ProxyFactoryFactoryClass,
							             "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle")
							.SetProperty(Environment.TransactionStrategy, "NHibernate.Transaction.AdoNetTransactionFactory")
							.SetProperty(Environment.CacheProvider, "NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache")
							.SetProperty(Environment.ConnectionDriver, typeof (SQLite20Driver).AssemblyQualifiedName)
							.SetProperty(Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider")
							.SetProperty(Environment.Isolation, "ReadCommitted")
							.SetProperty(Environment.ConnectionString, "Data Source=:memory:;Version=3;New=True;")
							.SetProperty(Environment.ShowSql,"True")
							.SetProperty(Environment.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
							.AddAssembly(Assembly.GetAssembly(typeof (Plan)));

			_sessionFactory = _configuration.BuildSessionFactory();
			Session = _sessionFactory.OpenSession();
			var schemaExport = new SchemaExport(_configuration);
			schemaExport.Execute(false, true, false, Session.Connection, null);
		}

		public void Dispose()
		{
			Session.Dispose();
		}
	}

Additional Features

Support for Schemas

SQLite doesn’t provide native support for schemas. We use SQL Server, and this led to a problem when any of our mappings pointed to tables in anything other than the dbo schema. A simple fix to this is to replace all periods with underscores prior to creating your session factory. This gives the desired behavior without requiring any modification to your mapping files.

                    if (_configuration == null)
                    {
                        _configuration = new Configuration()
                        //Configuation...
                        foreach (PersistentClass classMapping in _configuration.ClassMappings)
                        {
                            if (classMapping.Table.Name.Contains("."))
                                classMapping.Table.Name = classMapping.Table.Name.Replace(".", "_");
                        }
                    }

Working with AutoMockContainer

If you’re a user of Moq-Contrib’s AutoMockContainer (it must be patched to work with the latest version of Moq), you can register the Session object into the container to have it provided instead of a mocked session. It’s as simple as adding the following after creating your session object.

            MockContainer.Register(Session);

Testing with NHProf

If you use NHibernate Profiler (if you don’t, you should be), your SQLite database interaction can be monitored using that as well. Add an AssemblyInitialize (or your testing framework’s variant) to your InMemoryDatabaseTest class and all interactions will be profiled.

		[AssemblyInitialize]
		public static void AssemblyInit(TestContext testContext)
		{
			NHibernateProfiler.Initialize();
		}
»  Substance: WordPress   »  Style: Ahren Ahimsa Blog Flux Local - Utah
© Jason Staten 2009