Home > database >  Mocking IConfiguration's GetValue<string>(string a)
Mocking IConfiguration's GetValue<string>(string a)

Time:08-08

I'm struggling to understand why the following attempt to mock reading an appsettings.config key/value doesn't work.

Class constructor:

private readonly IConfiguration _config;

public Client(IConfiguration configuration)
{
    _config = configuration;
    var s = _config.GetValue<string>("endpoint");
}

Tests:

[TestClass]
public class ClientTests
{
    private readonly Mock<IConfiguration> _configMock;

    public ClientTests()
    {
        _configMock = new Mock<IConfiguration>();
        _configMock.Setup(x => x[It.Is<string>(s => s == "endpoint")]).Returns("testEndpoint");
    }

    [TestMethod]
    public async Task Test1()
    {
        var client = new Client(_configMock.Object);

        var result = await client.GetData();

        Assert.AreEqual(null, result);
    }
}

CodePudding user response:

You can't mock extensions methods. .GetValue<T> is an extension method.

You can always create a real configuration, with in process test values:

In process

IConfiguration config = new ConfigurationBuilder()
  ..AddInMemoryCollection(new []{
      new KeyValuePair<string, string>("endpoint","testEndpoint"),
      // Other values
   })
  .Build();

Environment variabels

// Set an enviroment value for the current process
Environment.SetEnvironmentVariable("endpoint", "testEndpoint", EnvironmentVariableTarget.Process);

// Build a config based on environment variables
IConfiguration config = new ConfigurationBuilder()
  .AddEnvironmentVariables()
  .Build();

If you still want to mock. You'll need to setup: GetSection(string key) see the source code: https://github.com/dotnet/runtime/blob/3b3645ecfd9591462132a7ba440c0a61c48ad924/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs#L189

  • Related