【发布时间】:2010-06-09 15:49:53
【问题描述】:
我有点不确定如何在我的 nunit 测试装置中管理会话。
在下面的测试夹具中,我正在测试一个存储库。我的存储库构造函数接受一个 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);
}
}
}
这是一个好方法还是我应该以不同的方式处理会话?
【问题讨论】:
-
从技术上讲,最好在每个单元测试(每次测试之前的新配置)上从一个完全干净的状态开始,但是这样运行大量测试需要很长时间,所以我使用了与您的版本非常相似的东西。
标签: nhibernate nunit