Code that interacts with a database, either directly or through an Object-Relational Mapping (ORM) library like NHibernate, is often quite difficult to test. This blog post looks at unit testing data access code using FluentNHibernate mappings, but it should apply just as well to vanilla NHibernate and other ORMs.
NHibernate provides interfaces for everything, which you theoretically could use to provide mocks to your code under test, but mocking complex 3rd-party library classes like this is not necessarily a good idea: you’d need to know exactly how your code was using the NHibernate API in order to do so. It’s best to think of NHibernate as part of your standard library and provide a real NHibernate session to your code under test.
The problem with this is that a real NHibernate session needs a real database. If you want to test with the same DB as your production code, this means keeping a database server running for your test, getting data into it, working out how to cope with multiple tests using the same database, etc… the resulting test runs are going to be slow and a lot of work to maintain.
Enter SQLite. It’s a single-DLL relational database management system (RDBMS) that can create a database from scratch for each test (so no worrying about setting up fixtures for tests running in parallel), in a single file on disk or in memory (the latter of which is *fast*). Using SQLite for unit tests is nothing new, but there are a lot of configuration options to consider, and I thought it would be worth documenting the end result that we arrived at when doing this sort of testing on our previous project.