2010-06-09 76 views
3

我有點不確定如何管理我的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); 
     } 
    } 
} 

這是一個好方法,還是應該以不同的方式處理會話?

+0

從技術上講,它可能是更好的開始在每個單元測試(每次測試前新配置)一個完全乾淨的狀態,但它會花費太長時間跑了很多關於這樣的測試,所以我使用類似你的版本的東西。 – Paco 2010-06-09 17:22:55

回答

1

這看起來不錯,但我會創建一個基類。看看Ayende是如何做到的。

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

+0

在這個基類中,Ayende正在爲所有測試創建一次db。我讀過,每次測試最好做一次。這仍然可以通過基類嗎? – 2010-06-09 16:05:21

+0

我剛剛實現了這個基類,它實際上非常好。絕對推薦。 – 2010-06-09 19:55:59