In this post I wrote about the use of app settings in Asp.Net Core. One thing that I didn’t cover at the time was the fact that, as an extension library, the configuration extensions weren’t very easy to include in unit tests. Of course the intention is that you read the configuration at the start, pass through a model class and no mocking is required.
However, sometimes you’ll find yourself wanting to mock out a particular setting. Before I get into this, this post is heavily based on this article which describes the same process.
The following is a code sample using Moq:
var configuration = new Mock<IConfiguration>(); var configurationSection = new Mock<IConfigurationSection>(); configurationSection.Setup(a => a.Value).Returns("testvalue"); configuration.Setup(a => a.GetSection("TestValueKey")).Returns(configurationSection.Object);
This will cause any call to get the app settings key “TestValueKey” to return “testvalue”. As is stated in the linked article, whilst GetValue is an extension method, GetSection is not, but is (internally) called by GetValue.
Thanks!
I am having trouble returning an int value. In our appsettings.json file we have a setting that is set to an int. I can’t seem to set this up in the mock data to be able to use it for tests. It seems to only allow strings for the return value.
Great post, helped me for a test case after migrating to Net Core, thanks!
Thanks !
A different way of tackling the problem, avoiding Mock and lots of setup noise:
The InMemoryConfiguration *almost* gave me what I needed, so I extended it so that you can amend values after building the configuration (Situation I had I didn’t know all the mocked values at the time of building the Configuration)
https://gist.github.com/martinsmith1968/9567de76d2bbe537af05d76eb39b1162
Unit test at the bottom shows usage
It’s quite neat. I’ve started to view passing the config around as a bit of an anti-pattern altogether – partly because of the need for these type of solutions, and partly because it’s dependency injection in name only: your class had to be aware of a, potentially complex, set of configuration. I feel a new post coming on about this, actually 🙂