How to read a Web.Config file while Unit Test debugging a shell?

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

ie:

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

Everything works fine when I try to debug it, but the main problem occurs when I debug the unit test case calling the same code above, instead of showing "configurationUrl" in AllKeys from APPSettings showing "TestProjectRetargetTo35Allowed", I also added the file web.config to the testcase project.

Any help would be appreciated Thanks.

0
c # unit-testing web-config
May 7 '14 at
source share
3 answers

I suggest you create some level of abstraction to get rid of the dependency on the ConfigurationManager. For example:

 public interface IConfigurationReader { string GetAppSetting(string key); } public class ConfigurationReader : IConfigurationReader { public string GetAppSetting(string key) { return ConfigurationManager.AppSettings[key].ToString(); } } 

You can then mock this interface in unit test.

+7
May 7 '14 at 9:09
source share

A simple fix would be to simply copy the web.config file from the .web project and paste it into the test project, renaming it app.config in the test project.

This is very bad, although in unit tests you should not rely on external dependencies, but to fix it anyway!

@Jon_Lindeheim has the cleanest method, however, abstracting away from the interface so you can stub the return value in your test!

+3
Jan 15 '16 at
source share

The problem is that you did not create the app.config file for your test project. You created the web.config , but this is completely ignored, since the test project is not a web project.

At the same time, @Jon_Lindeheim is absolutely right to introduce an abstraction layer on top of the ConfigurationManager . (The ConfigurationManager is an external dependency, which means your unit test is testing more than just SUT.)

+2
May 7, '14 at 13:39
source share



All Articles