Mock IConfiguration from net core


Problem

We use IConfiguration interface to get access for information of sections and connection strings from our appsettings.json. However, we also need to test our code by mocking this interface with our configurations.

Solution

Let’s look through example we have such appsetting.json

{
  "ConnectionStrings": {
    "default": "value",
    "key1": "value"
  },
  "section1": {
    "key0": "value",
    "key1": "value"
  }
}

Firstly we need only connection string to test our method. ConnectionStrings is a section, so let’s start from mocking section


    var mockConfSection = new Mock<IConfigurationSection>();
    mockConfSection.SetupGet(m => m[It.Is<string>(s => s == "default")]).Returns("mock value");    

Now we can return our mocked section from GetSection method of IConfiguration interface.

    var mockConfiguration = new Mock<IConfiguration>();
    mockConfiguration.Setup(a => a.GetSection(It.Is<string>(s=>s == "ConnectionStrings"))).Returns(_mockConfSection.Object);

Briefly research gave me that answer. Even so , if we dive deeper, we may see that GetConnectionString extension method looks like

public static string GetConnectionString(this IConfiguration configuration, string name)
{
    return configuration?.GetSection("ConnectionStrings")?[name];
}

It means that this method uses literal and after use name of subsection, but if we look to the documentation , we see that our full key is "ConnectionStrings:default"

As the result of all above we may optimize our test code

_configuration = new Mock<IConfiguration>();
_configuration.SetupGet(x => x[It.Is<string>(s=>s == "ConnectionStrings:default")]).Returns("mock value");

That’s enough.

Buy Me A Coffee

Related Posts

Avoid reflections of mappers and let Mapster generate mappers for you

Mapster generating tool for onion application

Predict Bitcoin price with ML.net

Live time series coin price predictor with machine learning

Throw exceptions from backend to frontend with blazor

One of advantages of using same code language on both frontend and backend

How to avoid violating of SOLID principles while extending service behaviours

Step by step extending service behaviour with decorator pattern respecting SOLID

Blazor render optimization

Best practices

.Net 6 brings application state to blazor webassembly server prerender

It kills strange blinking on screen

Must have libraries for blazor

List of best nuget packages

Blazor virtualize component

Lazy loading of big lists. Rendering optimization.

Blazor grpc - comunication optimization

Smaller and faster requests to your backend from blazor wasm

Free database for your blazor app

Don't pay for the cloud