简体   繁体   English

如何配置我的设置文件以使用单元测试?

[英]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.该库由两个应用程序使用:一个是 Windows 服务,另一个是执行一些注册表读写操作的命令行应用程序。 Each has a slightly different App.config file that is loaded from the library at start-up.每个都有一个略有不同的 App.config 文件,该文件在启动时从库中加载。 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.当我尝试从单元测试中使用这个库时,它无法加载,因为加载库的应用程序(可能是 nunit)没有带有适当键的 *.exe.config 文件。

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.我希望库在生产中从每个应用程序的 *.exe.config 加载设置,但如果运行单元测试,则从第三个位置加载。

Alternatively, just add an app.config file to your unit testing project that contains the relevant information.或者,只需将 app.config 文件添加到包含相关信息的单元测试项目中。

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.从你的类中提取你的依赖并使用依赖注入来注入数据。这样,你可以存根你的配置 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.如果您实际上只是在测试配置文件,您应该能够使用ConfigurationManager显式加载它,尽管我不建议对配置数据进行单元测试。 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.您最好的选择可能是在代理 class 中结束对配置数据的访问,您可以在运行时根据需要重定向 - 不要直接使用内置 API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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