Search code examples
c#configurationmoqxunit

How to setup mock data to getter property which is getting from IConfiguration.GetSection(key).Get<T>() in unit test case?


my base custom configuration method

public class BaseCustomConfigManager
{
    private readonly IConfiguration _configuration;
    public BaseCustomConfigManager(IConfiguration configuration)
    {
        _configuration = configuration;
    }
   
    public T GetConfigurationSection<T>(string key)
    {
        return _configuration.GetSection(key).Get<T>();
    }
}

and ICustomConfigurationManager setup

public interface ICustomConfigManager
{
   AwsConfig AwsConfig { get; }
   ...
}

and AwsConfig model properties

public class AwsConfig
{       
   public string BucketName { get; set; }
   public string AccessKey { get; set; }
   public string SecretKey { get; set; }
   ...
}

my CustomConfigManager service file to which I have to write test cases

public class CustomConfigManager : BaseCustomConfigManager, ICustomConfigManager
{
  private readonly IConfiguration _configuration;    
  public CustomConfigManager(IConfiguration configuration) : base(configuration)
  {
    _configuration = configuration;
  }
  public AwsConfig AwsConfig => GetConfigurationSection<AwsConfig>("testKey");
}

My unit test case for AwsConfig's in Xunit

[Fact]
public void GetConfigurationSection_WhenAwsConfigProperty_ReturnCorrespondingSection()
{
      //Arrange
    
      var objAwsMocData = new AwsConfig()
                {
                    BucketName = "storage",
                    AccessKey = "A1B2C3D4E5F6",
                    SecretKey = "6F5E4D3C2B1A",
                    ..
                };
    
      Mock<IConfiguration> configuration = new Mock<IConfiguration>();
      configuration.Setup(c => c.GetSection("testKey")).Returns(new Mock<IConfigurationSection>().Object);
    
      var mockICustomConfigManager = new Mock<ICustomConfigManager>();
      mockICustomConfigManager.Setup(x => x.AwsConfig).Returns(objAwsMocData);
      //Action
    
      var configManager = new CustomConfigManager(configuration.Object);
    
      var result = configManager.AwsConfig;
    
      //Assert
    
      _mockRepository.VerifyAll();
}

in result I couldn't getting anything, getting null only, for any assert action I need data, so how to setup for that?


Solution

  • Rather than trying to mock the IConfiguration,
    please try to use the in-memory configuration provider:

    //Arrange
    IConfiguration configRoot = new ConfigurationBuilder()
        .AddInMemoryCollection(new Dictionary<string, string>
        {
            { "testKey:BucketName", "storage" }, 
            { "testKey:AccessKey", "A1B2C3D4E5F6" },
            { "testKey:SecretKey", "6F5E4D3C2B1A" },
            ...
        })
        .Build();
        
    var configManager = new CustomConfigManager(configRoot);
    
    //Act
    ...