/ fluent nhibernate

Fluent NHibernate Mapping Tests

For months, I’ve been writing tons of mapping code for Fluent NHibernate and, although I love the framework, I hate that I can’t just create some criteria to make sure my mappings work. Yes, there’s some built in tools to verify your mappings. But, those tools assume a complete working data model. And, frankly, that’s not what I’m looking to test. I just want to know if my mappings are correct.

Last night, I came across this blog post and this is exactly what I’ve been looking for. It just tests the mappings. Okay, so you do need an in-memory Sqlite database to underlie the test, but it works. It just verifies the mappings in one single method and that’s a wonderful thing. Below is the code:

[Test] public void AllMappingsAreOk() { var session = GetCurrentNHibernateSession(); var errors = new List(); foreach (var entry in session.SessionFactory.GetAllClassMetadata()) { var type = entry.Key; var data = entry.Value; try { session.CreateCriteria(type).SetMaxResults(0).List(); } catch (Exception e) { errors.Add(string.Format("Error getting type {0}: {1}", type, e.Message)); } foreach (var collection in data.PropertyNames.Where(x => data.GetPropertyType(x).IsCollectionType)) { try { session.CreateCriteria(type).CreateCriteria(collection).SetMaxResults(0).List(); } catch (Exception e) { errors.Add(string.Format("Error getting collection {0}.{1}: {2}", type, collection, e.Message)); } } } Assert.True(errors.Count == 0, string.Join(Environment.NewLine, errors)); }

This solution is simple. All it does is create the query criteria for the underlying SQL call. If your mappings are broken, it will fail. So simple yet so powerful.