How to mock ConfigurationManager.AppSettings with moq

Otuyh picture Otuyh · Feb 28, 2012 · Viewed 73.7k times · Source

I am stuck at this point of code that I do not know how to mock:

ConfigurationManager.AppSettings["User"];

I have to mock the ConfigurationManager, but I don't have a clue, I am using Moq.

Someone can give me a tip? Thanks!

Answer

LosManos picture LosManos · Feb 19, 2014

I am using AspnetMvc4. A moment ago I wrote

ConfigurationManager.AppSettings["mykey"] = "myvalue";

in my test method and it worked perfectly.

Explanation: the test method runs in a context with app settings taken from, typically a web.config or myapp.config. ConfigurationsManager can reach this application-global object and manipulate it.

Though: If you have a test runner running tests in parallel this is not a good idea.