Terry Thibodeau's Blog

Welcome to Terry Thibodeau's Blog Sign in | Join | Help

Testing NHibernate object mappings in isolation (Part 2 - dependencies)

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);

 

* - A component is a contained object that is persisted as a value type, not an entity. See Component Mapping in the NHibernate documentation.

Published Monday, February 25, 2008 12:58 PM by Terry Thibodeau
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server (Personal Edition), by Telligent Systems