如何配置设置文件以与单元测试一起使用? [英] How do I configure my settings file to work with unit tests?

查看:183
本文介绍了如何配置设置文件以与单元测试一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要为其编写单元测试的库.该库由两个应用程序使用:一个是Windows服务,另一个是执行某些注册表读写的命令行应用程序.每个启动时都有一个略有不同的App.config文件,该文件是从库中加载的.例如:

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);
    }

当我尝试从单元测试中使用此库时,由于无法加载带有适当键的* .exe.config文件,因此无法加载该库,因为加载该库的应用程序(大概是nunit).

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.

有什么更好的方法?我希望该库从生产中的每个应用程序的* .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.

推荐答案

如果您的单元测试旨在测试代码,则完全不必依赖配置文件.从类中提取依赖项,并使用依赖项注入来注入数据.这样,您就可以对配置类进行存根处理.

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.

这篇关于如何配置设置文件以与单元测试一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆