Yes - that Jake.
Yes - that Jake.

Reputation: 17129

How do I configure my settings file to work with unit tests?

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.

Upvotes: 2

Views: 1659

Answers (3)

Michael Meadows
Michael Meadows

Reputation: 28426

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.

Upvotes: 2

ChrisLively
ChrisLively

Reputation: 88082

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

Upvotes: 3

Jeff Kotula
Jeff Kotula

Reputation: 2134

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.

Upvotes: 1

Related Questions