开发者

How to manage sessions in NHibernate unit tests?

开发者 https://www.devze.com 2023-01-02 17:12 出处:网络
I am a little unsure as to how to manage sessions within my nunit test fixtures. In the following test fixture, I am testing a repository. My repository constructor takes 开发者_如何学编程in an ISess

I am a little unsure as to how to manage sessions within my nunit test fixtures.

In the following test fixture, I am testing a repository. My repository constructor takes 开发者_如何学编程in an ISession (since I will be using session per request in my web application).

In my test fixture setup I configure NHibernate and build the session factory. In my test setup I create a clean SQLite database for each test executed.

    [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);
        }
    }
}

Is this a good approach or should I be handling the sessions differently?


This looks pretty good, but I would create as a base class. Check out how Ayende does it.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号