NHIBERNATE-使用ASP.NET MVC进行单位测试
-
08-10-2019 - |
题
我的ASP.NET MVC应用程序中的控制器取决于IdataContext,它是Nhibnerate会话周围的包装器,因此我稍后可以轻松地替换。我使用Microsoft Unity IOC容器将依赖项注入我的类构造函数。
我首先尝试在我的测试项目中创建了一个fakedatacontext,并设置正确的依赖项如下:
public class BaseControllerTest {
[TestInitialize]
public void Init() {
// Create the ioc container
var container = new UnityContainer();
// Setup the common service locator (must come before any instance registered that use the common service locator such as membership provider)
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
// Configure the container
container.RegisterType<IDataContext, FakeDataContext>();
}
}
现在,我要做的就是从这个课程中继承,一切正常,但是我觉得FakedataContext并不是执行测试的最准确方法,因此我尝试使用SQLite创建内存会话。我已将上述修改为:
public class BaseControllerTest {
private static Configuration _configuration;
[TestInitialize]
public void Init() {
// Create the ioc container
var container = new UnityContainer();
// Configure the container
container.RegisterType<ISessionFactory>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => {
return CreateSessionFactory();
}));
container.RegisterType<ISession>(new InjectionFactory(c => {
var sessionFactory = container.Resolve<ISessionFactory>();
var session = sessionFactory.OpenSession();
BuildSchema(session);
return session;
}));
container.RegisterType<IDataContext, NHibernateDataContext>();
}
private static ISessionFactory CreateSessionFactory() {
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.InMemory())
.Mappings(m => m.FluentMappings
.AddFromAssembly(Assembly.GetExecutingAssembly())
.Conventions.AddFromAssemblyOf<EnumConvention>())
.ExposeConfiguration(c => _configuration = c)
.BuildSessionFactory();
}
private static void BuildSchema(ISession session) {
var export = new SchemaExport(_configuration);
export.Execute(true, true, false, session.Connection, null);
}
}
但是,这引发了错误“创建SessionFactory时使用了无效或不完整的配置。”。我认为这可能是因为映射正在寻找的实体与测试项目不同,因此我尝试说assembly.loadfile(“ C:.. myassembly.dll”),但这仍然不起作用。
请注意,我使用了以下文章 http://www.mohundro.com/blog/commentview,guid,fa72ff57-5c08-49fa-979e-c732df2bf5f8.aspx 提供帮助,但这并不是我想要的。
如果有人可以提供帮助,我会很感激。谢谢
解决方案
问题解决了。我需要添加对sqlite dll的引用。我还更改了会话,以使用containerControlledLifetimeManager和Session Factory。如果有一种更有效的方法可以做到这一点,请纠正我。
不隶属于 StackOverflow