【问题标题】:How to manage sessions in NHibernate unit tests?如何管理 NHibernate 单元测试中的会话?
【发布时间】:2010-06-09 15:49:53
【问题描述】:

我有点不确定如何在我的 nunit 测试装置中管理会话。

在下面的测试夹具中,我正在测试一个存储库。我的存储库构造函数接受一个 ISession(因为我将在我的 Web 应用程序中使用每个请求的会话)。

在我的测试夹具设置中,我配置 NHibernate 并构建会话工厂。在我的测试设置中,我为每个执行的测试创建一个干净的 SQLite 数据库。

    [TestFixture]
public class SimpleRepository_Fixture
{
    private static ISessionFactory _sessionFactory;
    private static Configuration _configuration;

    [TestFixtureSetUp] // called before any tests in fixture are executed
    public void TestFixtureSetUp() {
        _configuration = new Configuration();
        _configuration.Configure();
        _configuration.AddAssembly(typeof(SimpleObject).Assembly); 
        _sessionFactory = _configuration.BuildSessionFactory();
    }

    [SetUp] // called before each test method is called
    public void SetupContext() {
        new SchemaExport(_configuration).Execute(true, true, false);
    }

    [Test]
    public void Can_add_new_simpleobject()
    {
        var simpleObject = new SimpleObject() { Name = "Object 1" };

        using (var session = _sessionFactory.OpenSession())
        {
            var repo = new SimpleObjectRepository(session);
            repo.Save(simpleObject);
        }

        using (var session =_sessionFactory.OpenSession())
        {
            var repo = new SimpleObjectRepository(session);
            var fromDb = repo.GetById(simpleObject.Id);

            Assert.IsNotNull(fromDb);
            Assert.AreNotSame(simpleObject, fromDb);
            Assert.AreEqual(simpleObject.Name, fromDb.Name);
        }
    }
}

这是一个好方法还是我应该以不同的方式处理会话?

【问题讨论】:

  • 从技术上讲,最好在每个单元测试(每次测试之前的新配置)上从一个完全干净的状态开始,但是这样运行大量测试需要很长时间,所以我使用了与您的版本非常相似的东西。

标签: nhibernate nunit


【解决方案1】:

这看起来不错,但我会创建一个基类。看看 Ayende 是如何做到的。

http://ayende.com/Blog/archive/2009/04/28/nhibernate-unit-testing.aspx

【讨论】:

  • 在这个基类中,Ayende 为所有测试创建了一次数据库。我读到最好每次测试执行一次。这仍然可以通过基类实现吗?
  • 我刚刚实现了这个基类,它实际上非常好。绝对推荐。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 2010-09-26
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
相关资源
最近更新 更多