もちろん状況によって異なりますが、ほとんどの場合、テストでリポジトリをモックし、マッピングをテストするためだけにインメモリSQLiteデータベースを使用するだけで十分だと思います(FluentNHibernate Persistence仕様テスト)。
SQLiteを使用したNUnitマッピングテストでは、次の基本クラスを使用しています。
public abstract class MappingsTestBase
{
[SetUp]
public void Setup()
{
_session = SessionFactory.OpenSession();
BuildSchema(_session);
}
[TestFixtureTearDown]
public void Terminate()
{
_session.Close();
_session.Dispose();
_session = null;
_sessionFactory = null;
_configuration = null;
}
#region NHibernate InMemory SQLite Session
internal static ISession _session;
private static ISessionFactory _sessionFactory;
private static Configuration _configuration;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
FluentConfiguration configuration = Fluently.Configure()
.Database(SQLiteConfiguration.Standard.InMemory().ShowSql)
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<NHibernateSession>())
.ExposeConfiguration(c => _configuration = c);
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
private static void BuildSchema(ISession session)
{
SchemaExport export = new SchemaExport(_configuration);
export.Execute(true, true, false, session.Connection, null);
}
#endregion
}
上記の基本クラスから派生したマッピングテストクラスの例は、次のようになります。
[TestFixture]
public class MappingsTest : MappingsTestBase
{
[Test]
public void Persistence_Employee_ShouldMapCorrectly()
{
Category employee = new PersistenceSpecification<Employee>(_session)
.CheckProperty(e => e.Id, 1)
.CheckProperty(e => e.FirstName, "John")
.CheckProperty(e => e.LastName, "Doe")
.VerifyTheMappings();
...
Assert.Equals(employee.FirstName, "John");
...
}
}