0

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.

MiBuena
  • 451
  • 3
  • 22
  • 1
    Check the following https://stackoverflow.com/a/64795010/5233410 – Nkosi Jun 16 '22 at 11:05
  • @Nkosi, yes, I saw this answer, but I really want to make it like a clean unit test. I don't want to use In-Memory providers. I found a solution for Moq, but I just can't get it to work for NSubstitute. https://stackoverflow.com/a/55189413/7654641 – MiBuena Jun 16 '22 at 11:19

0 Answers0