Cool Way to Fake IConfiguration for unit testing
I was working on a project the other day and I came across a need to fake/mock an IConfigutration object.
Tried MOQ
I started with MOQ. This is always quick and easy to use. I have used this in the past but this time I needed to change the values within the configuration. Which is totally possible but the more I dig into how to do that the more of a pain it became.
Since I am lazy, I figured there has to be a better way.
Simpler Method
I quickly discovered, there was an easier way.
There is a class in .Net called ConfigurationBuilder. With this class, you can easily create an in-memory configuration collection with whatever settings you want.
1. Create a dictionary of values
var inMemorySettings = new Dictionary<string, string>()
{
{ "Location", "TestLocation"}
};
2. Create the Configuration builder, adding the settings
config = new ConfigurationBuilder()
.AddInMemoryCollection(inMemorySettings)
.Build();
Usage
When I use this I actually place it the constructor of the unit test class instead of the setup when I can use the same object for all my tests. If I am varying the settings for different tests, I will create it with each test method.
Summary
Like most of what we do, this is just another way to solve the problem of handling application settings for unit testing.
Listed below is a Blazor sample application I used to demonstrate using this method when testing a class that needs application settings.
Comments
Post a Comment