Tuesday, 19 February 2008

Dynamic app.config settings for testing

If you need to write tests that verify behaviour based on different app.config settings, here’s a neat way of doing so.

In your [SetUp] method, load the app.config into two separate instances of the Configuration class, like so:

public void SetUp()
//load config so it can be edited for tests
_originalConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

_currentConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//any other init code here

In your [TearDown] method, ensure that you restore the app.config to the original (presumably you want it to be the same every time your tests start).

public void TearDown()
_currentConfig = _originalConfig;

When you need to modify any part of the config you can do so (provided there’s a “set” property for the element or attribute) at runtime like so:

public void MyTest()
//... set up stuff here ...

//modify config for this test. Set the lockout period to 120 minutes
//_client is an instance of a custom configuration element
int lockoutPeriod = 120;
_client.Profiles.PasswordLockoutPeriod = lockoutPeriod;

//... carry out your tests here ...

Pay particular attention to the call to ConfigurationManager.RefreshSection("clientSettings");. The change I made to the config is within this section and so I want to refresh it before continuing in order to ensure that the new version is used.

Also note that any objects that reference the config need to be re-loaded after you’ve modified (and refreshed) the config in order to get the changes. For example, if you have loaded an instance of a class in your SetUp that uses config you'll have to re-initialise that class after making your config changes in a test.

No comments: