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 ConfigurationElement
locking works, but I did find a workaround that seems fine for unit testing at least: before adding new items, set LockItem
to false.
So in my custom ConfigurationElementCollection
I have the method Add()
(which I'm calling in the OP). It needs to be modified to look like this:
public class TenantCollection : ConfigurationElementCollection
{
public void Add(Tenant element)
{
LockItem = false; // the workaround
BaseAdd(element);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With