用SQLite来单元测试Nhibernate的DataAccess
MVC如果要测试Controller,势必涉及到数据库访问,如果每次都访问同一个数据库必然造成与这个特定的数据库产生了耦合,因此用内存数据库SQLite来测试是最好不过的,同时也利于持续集成,每次测试都产生一个新的数据库,测试完成后废弃掉,以下是配置方式使用FluentNhibernate,需要注意的是构建Sechma的Session需要和数据访问的Session一致才行
public class NHConfigurator
{
public ISessionFactory _sessionFactory;
public static Configuration _configuration;
public ISession Session { get; set; }
public NHConfigurator()
{
_sessionFactory = CreateSessionFactory();
Session = _sessionFactory.OpenSession();
BuildSchema(Session);
}
private static void BuildSchema(ISession Session)
{
SchemaExport export = new SchemaExport(_configuration);
export.Execute(true, true, false, Session.Connection, null);
}
public ISessionFactory CreateSessionFactory()
{
if(_sessionFactory==null)
{
_sessionFactory = Fluently.Configure()
.Database(
SQLiteConfiguration.Standard.InMemory().ShowSql())//生成语句
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<your_mapping_class>())
.ExposeConfiguration(cfg =>_configuration=cfg
)
.BuildSessionFactory();
}
return _sessionFactory;
}
}
{
public ISessionFactory _sessionFactory;
public static Configuration _configuration;
public ISession Session { get; set; }
public NHConfigurator()
{
_sessionFactory = CreateSessionFactory();
Session = _sessionFactory.OpenSession();
BuildSchema(Session);
}
private static void BuildSchema(ISession Session)
{
SchemaExport export = new SchemaExport(_configuration);
export.Execute(true, true, false, Session.Connection, null);
}
public ISessionFactory CreateSessionFactory()
{
if(_sessionFactory==null)
{
_sessionFactory = Fluently.Configure()
.Database(
SQLiteConfiguration.Standard.InMemory().ShowSql())//生成语句
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<your_mapping_class>())
.ExposeConfiguration(cfg =>_configuration=cfg
)
.BuildSessionFactory();
}
return _sessionFactory;
}
}
posted on 2011-07-29 18:06 MoonWalker 阅读(274) 评论(0) 编辑 收藏 举报