我有点不确定如何管理我的nunit测试夹具中的会话。如何在NHibernate单元测试中管理会话?
在下面的测试夹具中,我测试了一个存储库。我的存储库构造函数需要一个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);
}
}
}
这是一个好方法,还是应该以不同的方式处理会话?
从技术上讲,它可能是更好的开始在每个单元测试(每次测试前新配置)一个完全干净的状态,但它会花费太长时间跑了很多关于这样的测试,所以我使用类似你的版本的东西。 – Paco 2010-06-09 17:22:55