Dot-Net

如何以程式方式將元素添加到 ConfigurationElementCollection?

  • January 7, 2014

我正在嘗試對 custom 進行單元測試ConfigurationElementCollection,但在以程式方式填充集合時遇到問題。當我打電話時BaseAdd(),我得到以下異常:

ConfigurationErrorsException :元素“添加”已被鎖定在更高級別的配置中。

但是,此問題僅在執行多個測試時出現。考慮這兩個測試:

private Fixture Fixtures = new Fixture();  // AutoFixtures

[Test]
public void test1()
{
   var tc = Fixtures.CreateAnonymous<TenantCollection>();
   var t = Fixtures.CreateAnonymous<Tenant>();
   tc.Add(t);
}

[Test]
public void test2()
{
   var tc = Fixtures.CreateAnonymous<TenantCollection>();
   var t = Fixtures.CreateAnonymous<Tenant>();
   tc.Add(t);
}

每個單獨的測試在單獨執行時都會通過。一起執行時,會拋出鎖定異常。

這裡發生了什麼?我怎樣才能解鎖收藏或解決該鎖?

我仍然不完全確定ConfigurationElement鎖定是如何工作的,但我確實找到了一個至少對於單元測試來說似乎很好的解決方法:在添加新項目之前,設置LockItem為 false。

所以在我的自定義中,ConfigurationElementCollection我有方法Add()(我在 OP 中呼叫)。它需要修改為如下所示:

public class TenantCollection : ConfigurationElementCollection
{
   public void Add(Tenant element)
   {
       LockItem = false;  // the workaround
       BaseAdd(element);
   }
}

引用自:https://stackoverflow.com/questions/10387141