I am developing Asp.net Core 6 Web Api project.
I have appsettings:
"MainSection": {
"FirstSubsection":{
"SomeKey": "someValue"
},
"SecondSubSection": {
SomeKey: "somevalue"
}
In the code I get "somevalue" through a typed model Foo in the following way:
configuration
.GetSection("MainSection")
.GetSection("SecondSection")
.Get<Foo>();
Foo is a typed class. .Get() method comes from Microsoft.Extensions.Configuration ConfigurationBuilder.
How do I mock Get() method in unit test using NSubstitute?
When I try to mock it like this, I get the error: Can not return value of type Foo for IDisposable.Dispose (expected type void).
var section = Substitute.For<IConfigurationSection>();
section.Get<Foo>().Returns(new Foo(){ SomeProperty = "aa"});
According to this answer NSubstitute can not mock extension methods.
I tried setting:
section.Key.Returns("SomeKey");
section.Value.Returns("someValue");
But the Get() method still returns null.
How can I mock it?
Edit: I need a solution similar to this, tried a million times, but I just can't get it to work with NSubstitute.