C# – How to mock ConfigurationManager.AppSettings with moq

cmoqunit testing

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!

Best Answer

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.