Search code examples
c#moqmstest

How to create and pass IConfiguration using MSTest


I have a concrete service that is declared in the form:

public class ApiDataService:IApiDataService
{
    private IConfiguration configuration;
    public ApiDataService(IConfiguration _configuration)
    {
        configuration = _configuration;
    }......

I'm trying to write a test method uising MsTest to test one of it's methods, but I'm having trouble initializing the class. As part of the test I need to get a value from the config file.

My initial thought was to declare a couple of mocks.:

private Mock<IConfiguration> _configuration = new Mock<IConfiguration>();
private Mock<IConfigurationSection> _configSection = new Mock<IConfigurationSection>();

ApiDataService _apiDataService { get; set; }

and then in the [TestInitialize] section set up the values and then create the new service.

_apiDataService = new ApiDataService(_configuration);

However I receive:

Cant convert Mock<IConfiguration> to IConfiguration.


Solution

  • Gladly yo don't need to mock the IConfiguration and IConfigurationSection interfaces.

    Rather than you can create an in-memory configuration, like this:

    IConfiguration configRoot = new ConfigurationBuilder()
        .AddInMemoryCollection(new Dictionary<string, string>
        {
            { "SingleKey", "Value" }, 
            { "ArrayOfValues:0", "Value1" },
            { "ArrayOfValues:1", "Value2" },
            { "ArrayOfValues:2", "Value3" }
        })
        .Build();
    

    And you can pass this object to your ApiDataService ctor.