How to manage sessions in NHibernate unit tests?

I'm a little unsure of how to manage sessions on my nunit meters.

In the next test device, I am testing a repository. My repository constructor accepts ISession (since I will use the session to query in my web application).

In configuring the test adapter, I configure NHibernate and create a factory session. In my test setup, I create a clean SQLite database for each test run.

    [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 handle the sessions differently?

+3
source share
1 answer

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

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

+1

Source: https://habr.com/ru/post/1749237/


All Articles