Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 762
Rahul Avatar asked Nov 29 '22 00:11

Rahul


2 Answers

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.

like image 155
Jon Lindeheim Avatar answered Dec 15 '22 04:12

Jon Lindeheim


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!

like image 24
Alex23 Avatar answered Dec 15 '22 03:12

Alex23