Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically add elements to a ConfigurationElementCollection?

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?

like image 952
ladenedge Avatar asked Apr 30 '12 16:04

ladenedge


1 Answers

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);
    }
}
like image 192
ladenedge Avatar answered Oct 14 '22 16:10

ladenedge