2013-03-02 70 views
0

我有一個奇怪的行爲,當一個單元測試成爲依賴另一個,並因NHiberante會話中的對象失敗。NHibernate.PropertyValueException:非空屬性引用空或瞬態和從屬單元測試

我得到'NHibernate.PropertyValueException:非空屬性引用空或瞬態'只有當我從燈具運行所有單元測試(爲簡單起見,我只有兩個測試)。如果我運行其中一個,它總是通過。

我覺得我應該做一些清理工作。我試過session.Clean()和session.Evict(obj),但它沒有幫助。有人能解釋這裏發生了什麼嗎?

實體:

public class Order 
{ 
    public virtual Guid Id { get; protected set; } 
    public virtual string Name { get; set; } 
} 

映射(與嘮叨API):

public class OrderMapping : ClassMapping<Order> 
{ 
    public OrderMapping() 
    { 
     Id(e => e.Id, m => 
      { 
       m.Generator(Generators.Guid); 
       m.Column("OrderId"); 
      }); 
     Property(e => e.Name, m => m.NotNullable(true)); 
    } 
} 

夾具構造函數(在內存中的數據庫中使用的):

var config = new Configuration(); 
config.CurrentSessionContext<ThreadStaticSessionContext>(); 
config.DataBaseIntegration(db => 
    { 
     db.ConnectionString = "uri=file://:memory:,Version=3"; 
     db.Dialect<SQLiteDialect>(); 
     db.Driver<CsharpSqliteDriver>(); 
     db.ConnectionReleaseMode = ConnectionReleaseMode.OnClose; 
     db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; 
     db.LogSqlInConsole = true; 
    }) 
    .SessionFactory() 
    .GenerateStatistics(); 

var mapper = new ModelMapper(); 
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes()); 
config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); 

ISessionFactory sessionFactory = config.BuildSessionFactory(); 
this.session = sessionFactory.OpenSession(); 

// This will leave the connection open 
new SchemaExport(config).Execute(
    true, true, false, this.session.Connection, null); 
CurrentSessionContext.Bind(this.session); 

單元測試:

[Test] 
[ExpectedException(typeof(PropertyValueException))] 
public void Order_name_is_required() 
{ 
    var order = new Order(); 
    this.session.Save(order); 
} 

[Test] 
public void Order_was_updated() 
{ 
    var order = new Order { Name = "Name 1" }; 
    this.session.Save(order); 

    this.session.Flush(); 

    order.Name = "Name 2"; 
    this.session.Update(order); 

    Assert.AreEqual(this.session.Get<Order>(order.Id).Name, "Name 2"); 
} 

訂單更新失敗,'NHibernate.PropertyValueException:not-null屬性引用空或瞬時'異常。實際上,如果寫入後其他任何單元測試都會失敗。

編輯1 找到了解決辦法。最後一次,當我試圖清理我用

[TestFixtureTearDown] 

,而不是

[TearDown] 
public void TearDown() 
{ 
    this.session.Clear(); 
} 

其中做了所有清理正確以前每次試運行的會話,並允許使用同一個會話和不要重新創建內存數據庫結構。 對不起,我犯了明顯的錯誤。

回答

0

不要重複使用同一個會話進行多個測試。另外,根據NHibernate文檔,如果會話/事務內部已經生成了異常,則會話不保證處於一致狀態,並且必須在沒有進一步使用的情況下進行處理。

+0

試圖避免爲每個單元測試創​​建會話,因爲在內存數據庫的情況下,它意味着重新創建整個數據庫結構,因爲數據庫僅在連接打開時存在。 – Loki 2013-03-03 10:01:38

相關問題