I thought I should post an update to "Testing NHibernate object mappings in isolation" as that post didn't address dependent objects in your mapping files. For a simple mapping to a class with only fields or component object references*, the previous method works fine.
When you start adding references to other entities in your mapping files, you must also add those mapping file references to the Configuration object. I've refactored the code from the previous post to load the mapping file resource based on the class type. Notice the test, "Should_map_Conference_class", adds its dependencies to the configuration.
private const string mappingFileAssemblyName = "Namespace.NHibernateMappings";
private readonly string customConfigPath = Path.Combine(Directory.GetCurrentDirectory(), @"localNHibernate.cfg.xml");
private Configuration configuration;
[SetUp]
public void TestInitialize()
{
configuration = new Configuration()
.Configure(customConfigPath);
}
[TearDown]
public void TearDown()
{
this.configuration.BuildSessionFactory().Close();
}
[Test]
public void Should_map_Conference_class()
{
AddSingleClass(typeof (Address));
AddSingleClass(typeof (Category));
AddSingleClass(typeof(Conference));
}
private Configuration AddSingleClass(Type persistentClassType)
{
Assembly assembly = Assembly.Load(mappingFileAssemblyName);
return this.configuration.AddResource(mappingFileAssemblyName + "." + persistentClassType.Name + ".hbm.xml", assembly);
}
If I were using C# 3.0 on this project, I could create an extension method for the NHibernate Configuration class to allow me to do something like:
configuration.AddSingleClass(typeof (Address), assembly)
.AddSingleClass(typeof(Category), assembly)
.AddSingleClass(typeof(Conference), assembly);