Home > database >  How to Mock IConfiguration.GetValue<string>
How to Mock IConfiguration.GetValue<string>

Time:10-25

I'm trying to mock the configuration, but urlVariable keeps returning null, I also could not mock GetValue since it's static extionsion under Configuration Builder

public static T GetValue<T>(this IConfiguration configuration, string key); 

Here's what I tried so far

// Arrange
var mockIConfigurationSection = new Mock<IConfigurationSection>();
mockIConfigurationSection.Setup(x => x.Value).Returns("SomeUrl");
mockIConfigurationSection.Setup(x => x.Key).Returns("Url");

var configuration = new Mock<IConfiguration>();
configuration.Setup(c => c.GetSection(It.IsAny<String>())).Returns(mockIConfigurationSection.Object);

// Act
var result = target.Test();

The method

public async Task Test()
{
var urlVariable = this._configuration.GetValue<string>("Url");
}

trying to mock these from app settings

{
"profiles": {
            "LocalDB": {
                        "environmentVariables": {
                                                "Url" : "SomeUrl"
                                                }
                       }
            }
}

CodePudding user response:

Maybe you are not instantiating target properly. This piece of code should work.

void Main()
{
    // Arrange
    var mockIConfigurationSection = new Mock<IConfigurationSection>();
    mockIConfigurationSection.Setup(x => x.Value).Returns("SomeUrl");
    mockIConfigurationSection.Setup(x => x.Key).Returns("Url");

    var configuration = new Mock<IConfiguration>();
    configuration.Setup(c => c.GetSection(It.IsAny<String>())).Returns(mockIConfigurationSection.Object);
    var target = new TestClass(configuration.Object);
    
    // Act
    var result = target.Test();
    
    //Assert
    Assert.Equal("SomeUrl", result);
}

public class TestClass 
{
    private readonly IConfiguration _configuration;
    public TestClass(IConfiguration configuration) { this._configuration = configuration; }
    public string Test()
    {
        return _configuration.GetValue<string>("Url");
    }
 }

Also, you might want to explore OptionsPattern

CodePudding user response:

You don't need to mock something which can be set created manually.
Use ConfigurationBuilder to setup expected values.

[Fact]
public void TestConfiguration()
{
    var value = new KeyValuePair<string, string>(
        "profiles:LocalDb:environmentVariable:Url", 
        "http://some.url"
    );            
    var configuration = new ConfigurationBuilder()
        .AddInMemoryCollection(new[] { value })
        .Build();

    var actual = 
        configuration.GetValue<string>("profiles:LocalDb:environmentVariable:Url");

    actual.Should().Be("http://some.url");
}
  • Related