【问题标题】:Unit testing an nHibernate repository - how to add to repository?对 nHibernate 存储库进行单元测试 - 如何添加到存储库?
【发布时间】:2013-04-12 13:37:06
【问题描述】:

我刚刚收到一个未完成的 asp.Net MVC 3 / nHibernate 项目来修复和完成,我正在尝试让已经通过的 nUnit 单元测试。

存储库测试是导致问题的原因。我想要做的只是向测试存储库添加几个项目,但如果我能弄清楚如何做到这一点,我会很高兴。情况如下:

[Test]
public void CanGetAllThings()
{
    ServiceLocatorInitializer.Init();

    ThingRepository thingRepository = new ThingRepository(); // ThingRepository inherits from NHibernateRepository<T>, IRepository<T>

    Thing thingA = new Thing { /*initialization values*/ };
    Thing thingB = new Thing { /*initialization values*/ };

    componentAuthorizationRepository.DbContext.BeginTransaction(); 

    ThingRepository.Save(ThingA); // Doesn't appear to be doing anything
    ThingRepository.Save(ThingB);

    componentAuthorizationRepository.DbContext.CommitTransaction(); 

    ThingRepository.GetAll().ShouldNotBeNull(); // Passes
    ThingRepository.GetAll().Count.ShouldEqual(2); // Fails with actual value 0 
}

我应该使用模拟框架来创建内存数据库吗?对于这样一个简单的测试来说,这似乎有点过头了,应该只有一个 Repository.Add() 或 Repository.Save() 方法,但我显然在这里遗漏了一些重要的东西。

我是一名初级开发人员,刚接触 MVC、nHibernate 和单元测试,所以我什至不清楚我的知识差距在哪里,所以我可以研究!任何指针都非常感谢。

【问题讨论】:

    标签: asp.net-mvc nhibernate nunit


    【解决方案1】:

    由于您已注释掉事务,因此您的 Save() 操作不会被提交。您需要以某种方式将事务管理添加到您的存储库,或者有一个工作单元来为您管理它。

    或者,如果你想要快速和肮脏,你需要一种在存储库的 ISession 上调用 Flush() 的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 2021-10-06
      相关资源
      最近更新 更多