如何在单元测试用例调试时读取 Web.Config 文件? [英] How to read Web.Config file while Unit Test Case Debugging?
问题描述
我正在尝试从我的配置文件中获取数据(URL)
I am trying to fetch data(URL) from my configuration file
即:
<AppSettings>
<add key="configurationUrl" value="http://xx.xx.xx.xx:XXXX/configuration service/configurations"/>
使用以下代码
reqClient.BaseAddress = System.Configuration.ConfigurationManager.AppSettings["configurationUrl"].ToString();
当我尝试调试它时一切正常,但是当我调试调用上面相同代码的单元测试用例时,主要问题出现了,而不是在 APPSettings 的 AllKeys 中显示configurationUrl",而是显示TestProjectRetargetTo35Allowed".我还在测试用例项目中添加了 web.config 文件.
Its all working good when I am trying to debug it, but the major problem comes when I debug a unit test case calling the same code above, instead of Showing "configurationUrl" in the AllKeys of APPSettings its showing "TestProjectRetargetTo35Allowed". I have also added the web.config file in the testcase project.
任何帮助将不胜感激谢谢.
Any assistance will be appreciated Thank You.
推荐答案
我建议你创建一些抽象层来摆脱对 ConfigurationManager 的依赖.例如:
I suggest you create some abstraction layer to get rid of the dependency to ConfigurationManager. For example:
public interface IConfigurationReader
{
string GetAppSetting(string key);
}
public class ConfigurationReader : IConfigurationReader
{
public string GetAppSetting(string key)
{
return ConfigurationManager.AppSettings[key].ToString();
}
}
然后你可以在你的单元测试中模拟这个接口.
Then you could mock this interface in your unit test.
这篇关于如何在单元测试用例调试时读取 Web.Config 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!