Filip Mellqvist
Filip Mellqvist

Reputation: 103

Mock class with constructor that takes IConfiguration as parameter

I want to mock class IncidentData.

The class with constructor:

public class IncidentData
{
    public IncidentData(IConfiguration configurationRoot)
    {
        configurationRoot.GetSection("CarambaAttributeData").Bind(this);
    }
}

I've tried to send setup a mock like so:

var incidentDataMock = new Mock<IncidentData>();
incidentDataMock.Setup(x => It.IsAny<IConfiguration>());

This gets me "System.ArgumentOutOfRangeException: Index was out of range"

Should I mock IConfiguration? How do I do that? What's the best practice?

Upvotes: 0

Views: 645

Answers (2)

Peter Csala
Peter Csala

Reputation: 22829

According to my understanding you are looking for a way to mock the configurationRoot parameter of the ctor instead of the whole IncidentData class.

All you need to do is create a memory collection then register a memory collection provider for the configuration instance.

var carambaAttributeDataConfig = new Dictionary<string, string>
{
   {"CarambaAttributeData:Key1", "Value1"},
   {"CarambaAttributeData:Key2", "Value2"},
   ...
   {"CarambaAttributeData:KeyN", "ValueN"},
};

IConfiguration config = new ConfigurationBuilder()
    .AddInMemoryCollection(carambaAttributeDataConfig)
    .Build();

var incidentDataMock = new IncidentData(config);

Reference

Upvotes: 0

Nkosi
Nkosi

Reputation: 247413

This is most likely an XY problem. What are you actually trying to achieve by mocking that class?

As for the error, you would need to pass the argument when creating the mock

For example

//...

IConfiguration config = Mock.Of<IConfiguration>();
var incidentDataMock = new Mock<IncidentData>(config); //<--NOTE constructor argument passed.

//...

or using an actual IConfiguration instance

//...

IConfiguration config = new ConfigurationBuilder()
    //...all extensions here
    //...
    .Build();
var incidentDataMock = new Mock<IncidentData>(config); //<--NOTE constructor argument passed.

//...

Reference Moq Quickstart to get a better understanding of how to use the library

Upvotes: 0

Related Questions