How to read Web.Config file while Unit Test Case Debugging?

a 夏天 提交于 2019-12-23 17:12:45

问题


I am trying to fetch data(URL) from my configuration file

i.e :

<AppSettings>
<add key="configurationUrl" value="http://xx.xx.xx.xx:XXXX/configuration service/configurations"/>

using the following code

 reqClient.BaseAddress = System.Configuration.ConfigurationManager.AppSettings["configurationUrl"].ToString();

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.


回答1:


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.




回答2:


An easy fix would be to simply copy the web.config over from the .web project and paste into your test project, renaming it to app.config in the test project.

This is very bad though as unit tests should not rely on external dependencies, but a fix none the less!

@Jon_Lindeheim has the cleanest method however by abstracting to interface so that you can stub the return value in your test!




回答3:


The issue is that you haven't created an app.config file for your test project. You've created a web.config file, but that's getting completely ignored since the test project isn't a web project.

That being said, @Jon_Lindeheim is absolutely right about introducing an abstraction layer on top of the ConfigurationManager. (The ConfigurationManager is an external dependency, which means your unit test is testing more than just the SUT.)



来源:https://stackoverflow.com/questions/23513355/how-to-read-web-config-file-while-unit-test-case-debugging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!