Hope Michaelson
Hope Michaelson

Reputation: 31

How to mock iconfiguration.GetSection(MyNodeName).Get<MyClassObject>()

I have a node in appsettings.json file which looks like this

"MyClassName": {
    "MyList1": ["x","y"],
    "MyList2": ["a","b","c"]
}

To save and use these lists I have a Class in my backend with 2 properties

public class MyClass
 {
    public List<string> MyList1 { get; set; }
    public List<string> MyList2 { get; set; }
 }

There is a method which populates these properties using IConfiguration like this

_iconfiguration.GetSection("MyClassName").Get<MyClass>();

I need to mock above line of code in my .NET Core application. For mocking I am using Moq(4.16.1) I tried to mock it like this

_mockConfiguration
    .Setup(m => m.GetSection(It.IsAny<string>()).Get<Myclass>())
    .Returns(MyClassObject);

But I am obviously missing something since I am getting Unsupported expression error. The error says something like this

Extension methods (here: ConfigurationBinder.Get) may not be used in setup / verification expressions.'

Is there a way to achieve this?

Upvotes: 3

Views: 3767

Answers (1)

Nkosi
Nkosi

Reputation: 247413

You get the exception because the Get in this case is an extension method and MOQ does not mock extensions

No need to mock IConfiguration. An actual instance can be built with in-memory configuration to get the desired behavior.

//Arrange
Dictionary<string, string> inMemorySettings =
    new Dictionary<string, string> {
        {"MyClassName:MyList1:0", "x"},
        {"MyClassName:MyList1:1", "y"},
        {"MyClassName:MyList2:0", "a"},
        {"MyClassName:MyList2:1", "b"},
        {"MyClassName:MyList2:2", "c"},
    };

IConfiguration configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(inMemorySettings)
    .Build();

//...

The above will allow the IConfiguration instance to be used as needed.

Reference Memory Configuration Provider

Upvotes: 7

Related Questions