我的ASP.NET MVC应用程序中的控制器依赖于IDataContext,它是nhibenerate会话的包装器,以便以后可以轻松地替换它。我使用MicrosoftUnityIOC容器在类的构造函数中注入依赖项。
我首先尝试在测试项目中创建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
但这并不是我想要的。
如果有人能帮忙,我将不胜感激。谢谢