views:

105

answers:

3

I have a library I'm writing unit tests for. The library is used by two applications: one a Windows service, the other a command-line application that does some registry read-writes. Each has a slightly different App.config file that is loaded from the library at start-up. For example:

    public RetentionService()
    {
        SettingHive = new Hive();
        TimingService = new RetentionTimingService(SettingHive);

        AppSettingsReader asr = new AppSettingsReader();
        object appsListObj = asr.GetValue(@"blocking-process-list", Type.GetType(@"System.String"));
        string appsList = appsListObj.ToString();
        _BlockingAppNames = RetentionService.ListFromList(appsList);

        string targetList = asr.GetValue(@"target-files", Type.GetType(@"System.String")).ToString();
        _TargetLogs = RetentionService.ListFromList(targetList);
    }

When I try to use this library from a unit test, it fails to load because the application loading the library (presumably nunit) doesn't have a *.exe.config file with the appropriate keys.

What's a better way to do this? I'd like the library to load the settings from each application's *.exe.config in production, but from a third location if running a unit test.

+1  A: 

Your best bet may be to wrap up access to the config data within a proxy class that you can redirect as needed at runtime -- don't use the builtin APIs directly.

Jeff Kotula
+3  A: 

If your unit tests are designed to test the code, then don't depend on the config file at all. Extract your dependency out of your classes and use dependency injection to inject the data in. That way, you can stub your configuration class.

If you are actually just testing your configuration file, you should be able to load it explicitly using ConfigurationManager, although I wouldn't suggest unit testing configuration data. It's a better candidate for smoke testing.

Michael Meadows
+1  A: 

Alternatively, just add an app.config file to your unit testing project that contains the relevant information.

Chris Lively