My Writings. My Thoughts.
Fluent NHibernate - verifying mappings with reflection
// March 9th, 2009 // .Net, NHibernate
I recently started to evaluate Fluent NHibernate which is a handy tool for getting rid of the NHibernate mapping XML files. I’m not going to go into more detail on either NHibernate itself or Fluent NHibernate in this post. Instead I’m going to share a nifty little piece of code I crafted to automate the process of verifying the mappings you create. Fluent NHibernate has a very useful generic class called PersistenceSpecification. You use it like this:
new PersistenceSpecification<Order>(Session).VerifyTheMappings();
By just executing the VerifyTheMappings method in your unit tests you instantly see if something is wrong with you mappings. Very nice! Now, you could add this line of code for each mapping class you have, and all would be well. But then again you might forget to add that line when creating new mappings. Wouldn’t it be nice if there was a way to make your unit test automatically find new mapping classes and test them for you? By using a little bit of reflection magic I ended up with this:
protected virtual void VerifyFluentMappingsByReflection(Assembly assembly) { // Get all mapping types to test foreach (System.Type type in assembly.GetTypes()) { // Make sure it is a generic type if (!type.BaseType.IsGenericType) continue; // Check if it inherits from FluentNHibernate.Mapping.ClassMap<> if (type.BaseType.GetGenericTypeDefinition().Equals(typeof(FluentNHibernate.Mapping.ClassMap<>))) { // Invoke VerifyTheMappings() Type typeGeneric = typeof(PersistenceSpecification<>); Type typeConcrete = typeGeneric.MakeGenericType(new Type[] { type.BaseType.GetGenericArguments()[0] }); Object specificationObject = Activator.CreateInstance(typeConcrete, Session); MethodInfo verifyTheMappingsMethodInfo = typeConcrete.GetMethod("VerifyTheMappings"); verifyTheMappingsMethodInfo.Invoke(specificationObject, null); } } }
You can use this method in a unit test. Just add it to a class and execute it by passing in the assembly where your keep your mappings. Feel free to use the code in any way you like, and please give me a shout in the comments if you like it!

