How to manage sessions in NHibernate unit tests?
- by Ben
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