Unit testing NHibernate mappings

When someone starts to learn NHibernate, a very popular question is: which approach you should use to map your domain classes to the database? Currently, the answer can be HBM files, Fluent NHibernate or Mapping By Code.

After doing some research, I believe that the best answer is: as long as you have good Unit Tests in place, it doesn’t really matter. At the end of the day, the same mapping issue that you will face using HBM files, you will face using FHN or Mapping By Code.

Because of that, I did some experiments on what would be a good approach to unit test NHibernate mappings. For that, I will be using NUnit and SQLite.

Project Setup

All the source code used in this post is also available here. The NuGet packages used were the following.

The library NUnit3TestAdapter is all you need to run NUnit unit tests from any version of Visual Studio.

Using an In-Memory Helper Class

This is the NHibernate helper class that we will be using to open new connections. It is designed to create an in-memory instance of SQLite database per unit test class or unit test method. Doing so, you can isolate your unit tests with its own contained database.

Base Test Fixture Class

This is the BaseInMemoryFixture class that is designed to create a new instance of the database for each Test Fixture. It will help us create a new instance of InMemorySessionHelper for each unit test. For what I did so far, running them per test class was enough.

The OpenSession method will be used to create new sessions inside each unit test. The in-memory database will stay alive until the connection is open. The TearDown method will be responsible for disposing of the session helper, which will close the connection.

A Sample Mapping Unit Test

This is a sample test to demonstrate how we can extend the BaseInMemoryFixture class to execute a unit test that validates the data mapping for a Template Fields property.

The point here is that you don’t need to hit a real database or even your development database, to validate that your ORM is working as expected.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s