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!
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!
I believe one standard approach to this is to use a facade pattern to wrap the configuration manager and then you have something loosely coupled that you have control over.
So you would wrap the ConfigurationManager. Something like:
public class Configuration: IConfiguration
{
public User
{
get
{
return ConfigurationManager.AppSettings["User"];
}
}
}
(You can just extract an interface from your configuration class and then use that interface everywhere in your code) Then you just mock the IConfiguration. You might be able to implement the facade itself in a few different ways. Above I chose just to wrap the individual properties. You also obtain the side benefit of having strongly typed information to work with rather than weakly typed hash arrays.
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.
Maybe is not what you need to accomplish, but have you considered to use an app.config in your test project? So the ConfigurationManager will get the values that you put in the app.config and you don't need to mock anything. This solution works nice for my needs, because I never need to test a "variable" config file.
You can use shims to modify AppSettings
to a custom NameValueCollection
object. Here is an example of how you can achieve this:
[TestMethod]
public void TestSomething()
{
using(ShimsContext.Create()) {
const string key = "key";
const string value = "value";
ShimConfigurationManager.AppSettingsGet = () =>
{
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection.Add(key, value);
return nameValueCollection;
};
///
// Test code here.
///
// Validation code goes here.
}
}
You can read more about shims and fakes at, Isolating Code Under Test with Microsoft Fakes. Hope this helps.
Have you considered stubbing instead of mocking? The AppSettings
property is a NameValueCollection
:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// Arrange
var settings = new NameValueCollection {{"User", "Otuyh"}};
var classUnderTest = new ClassUnderTest(settings);
// Act
classUnderTest.MethodUnderTest();
// Assert something...
}
}
public class ClassUnderTest
{
private readonly NameValueCollection _settings;
public ClassUnderTest(NameValueCollection settings)
{
_settings = settings;
}
public void MethodUnderTest()
{
// get the User from Settings
string user = _settings["User"];
// log
Trace.TraceInformation("User = \"{0}\"", user);
// do something else...
}
}
The benefits are a simpler implementation and no dependency on System.Configuration until you really need it.
That is a static property, and Moq is designed to Moq instance methods or classes that can be mocked via inheritance. In other words, Moq is not going to be any help to you here.
For mocking statics, I use a tool called Moles, which is free. There are other framework isolation tools, like Typemock that can do this too, though I believe those are paid tools.
When it comes to statics and testing, another option is to create the static state yourself, though this can often be problematic (as, I'd imagine it would be in your case).
And, finally, if the isolation frameworks are not an option and you're committed to this approach, the facade mentioned by Joshua is a good approach, or any approach in general where you factor client code of this away from the business logic that you're using to test.
I think writing you own app.config provider is a simple task and is more useful then anything else. Especially you should avoid any fakes like shims etc. because as soon as you use them Edit & Continue no longer works.
The providers I use look like this:
By default they get the values from the App.config
but for unit tests I can override all values and use them in each test independently.
There's no need for any interfaces or implement it each time over and over again. I have a utilities dll and use this small helper in many projects and unit tests.
public class AppConfigProvider
{
public AppConfigProvider()
{
ConnectionStrings = new ConnectionStringsProvider();
AppSettings = new AppSettingsProvider();
}
public ConnectionStringsProvider ConnectionStrings { get; private set; }
public AppSettingsProvider AppSettings { get; private set; }
}
public class ConnectionStringsProvider
{
private readonly Dictionary<string, string> _customValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public string this[string key]
{
get
{
string customValue;
if (_customValues.TryGetValue(key, out customValue))
{
return customValue;
}
var connectionStringSettings = ConfigurationManager.ConnectionStrings[key];
return connectionStringSettings == null ? null : connectionStringSettings.ConnectionString;
}
}
public Dictionary<string, string> CustomValues { get { return _customValues; } }
}
public class AppSettingsProvider
{
private readonly Dictionary<string, string> _customValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public string this[string key]
{
get
{
string customValue;
return _customValues.TryGetValue(key, out customValue) ? customValue : ConfigurationManager.AppSettings[key];
}
}
public Dictionary<string, string> CustomValues { get { return _customValues; } }
}
Another way to achieve this goal is to just provide your own IConfiguration
, pulling from any file you'd like it to pull from, like this:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
Now, as long as you have the values you need for testing in this JSON file, it's very easy to override and change values.