0
votes

I have an NUnit test project that is testing a Console App project. The Console app project uses the app.config file heavily. When running tests from my NUnit test project, the code being tested uses the config values in my Tests.dll.config file. This file is located in my Test project's root directory and is a copy of the app.config file from the app being tested.

However, in some tests I need to change the value of some of the config settings. I have been using this in my Nunit test to do it:

ConfigurationManager.AppSettings.Set("SettingKey" , "SettingValue");

I don't want these runtime config changes I make in one test to interfere or be seen by any other tests. Is this the correct way to do it?

UPDATE I should also mention that my tests run in parallel. I think this is because I am using Re-sharper. So if I change the config in one test I think it may change the config in another test, which I don't want.

2

2 Answers

1
votes

Is it possible to wrap code reading configuration in a interface? For example:

public interface IAppSettings
{
   string Get(string settingKey);
}

So you can easily abstract from the app.settings file. Then in your NUnit project you can implement IAppSettings by a simple class and configure your app to use it. In that case you don't need to read a real app.config file and can easily change configuration. It will also speed up your tests.

1
votes

It seems you are interested in an integration test and not a unit test. The reason being that your tests need to access the configuration file modify some values so your tests can run correctly.

You said you don't want your runtime config changes to interfere with other tests. The best way to handly this is to use NUnit built-in test initialize and tear-down approach.

For example, you can use A. NUnit [setup] attribute make runtime changes to your config

B. NUnit [teardown] attribute rollback the changes you did

See more info http://www.nunit.org/index.php?p=setup&r=2.2.10

Note each that each and every test in your class would run the above setup/teardown sequence.

So if you need more customized approach, you can simply create your own setup method and call it from the test you need after ther assert call a tear-down method to clean-up/rollback what you did in your setup method. This way it's only affecting for the tests you need it to change config values.

For example (in pseudo code)

Public void Mytestmethod()
       Call my own test init
       Call SUT
       Perform Any asserts
       Call My own tear down