I’m trying to unit test a custom ConfigurationElementCollection, but I’m having a problem populating the collection programmatically. When I call BaseAdd(), I get the following exception:
ConfigurationErrorsException : The element ‘add’ has been locked in a higher level configuration.
However, this problem only appears when running multiple tests. Consider these two tests:
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);
}
Each individual test passes when executed alone. When run together, the locking exception is thrown.
What’s going on here? How can I either unlock the collection or work around that lock?
I’m still not entirely sure how
ConfigurationElementlocking works, but I did find a workaround that seems fine for unit testing at least: before adding new items, setLockItemto false.So in my custom
ConfigurationElementCollectionI have the methodAdd()(which I’m calling in the OP). It needs to be modified to look like this: