views:

39

answers:

1

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?

Thanks Ben

+1  A: 

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

Corey Coogan
@Corey - In this base class Ayende is creating the db once for all tests. I read that it is better to do this once per test. Is this still possible through the base class?
Ben
I've just implemented this base class and it's actually very good. Definitely recommended.
Ben