So, wouldn't it be nice if declaring a test fixture with NH-support would be as easy as this:
As you can see, you just have to specify the name of the assembly with the relevant NH mappings in the constructor, together with the database credentials, and that's it. The base class then creates the appropriate SessionFactory instance for you on the fly, without any additional configuration. Here it is:
using System.Reflection;
using NHibernate;
using NHibernate.ByteCode.Castle;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using Environment=NHibernate.Cfg.Environment;
namespace DbDevelopment.Persistence.Test.Common
{
/// <summary>
/// Base class for a test fixture with NHibernate + MS SQL Server support.
/// </summary>
/// <remarks>
/// Use the c'tor to specify the mapping-assembly and the database credentials.
/// </remarks>
public abstract class NHibernateFixtureBase
{
#region Fields
protected ISessionFactory SessionFactory;
#endregion // Fields
#region Construction
protected NHibernateFixtureBase(string assemblyWithMappings,
string serverName, string databaseName,
string username, string password)
{
CreateSessionFactory(
assemblyWithMappings,
BuildConnectionString(serverName, databaseName, username, password));
}
#endregion // Construction
#region Implementation
private void CreateSessionFactory(string assemblyName, string connectionString)
{
Assembly assemblyWithMappings = Assembly.Load(assemblyName);
this.SessionFactory = new Configuration()
.SetProperty(Environment.ReleaseConnections, "on_close")
.SetProperty(Environment.Dialect, typeof(MsSql2005Dialect).AssemblyQualifiedName)
.SetProperty(Environment.ShowSql, "true")
.SetProperty(Environment.ConnectionDriver, typeof(SqlClientDriver).AssemblyQualifiedName)
.SetProperty(Environment.ConnectionString, connectionString)
.SetProperty(Environment.ProxyFactoryFactoryClass,typeof(ProxyFactoryFactory).AssemblyQualifiedName)
.AddAssembly(assemblyWithMappings)
.BuildSessionFactory();
}
private static string BuildConnectionString(string serverName, string databaseName,
string username, string password)
{
return string.Format(
"Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
serverName, databaseName, username, password);
}
#endregion // Implementation
} // class NHibernateFixtureBase
} // namespace DbDevelopment.Persistence.Test.Common
This example uses a MS SQL Server database (2005 or higher), but it could be easily modified to target a different DBMS by adjusting the BuildConnectionString() method along with the relevant configuration settings in CreateSessionFactory() accordingly.
Happy testing...