简体   繁体   中英

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM