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.
All the source code used in this post is also available here. The NuGet packages used were the following.
- For the Domain library project: none.
- For the Persistence library project: NHibernate and System.Data.SQLite.Core.
- For the Tests library project: NHibernate , System.Data.SQLite.Core, NUnit and NUnit3TestAdapter.
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.