2

I'm trying to mock the IConfiguration as well as the IConfigurationSection using NSubstitute. I have a custom configuration file that I use to configure HTTP clients on startup. The problem is when I try to mock, I cannot make it return my custom class ClientConfiguration using a .Returns(). I get this error:

NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException: 'Can not return value of type ClientConfiguration for IDisposable.Dispose (expected type void)'

Code:

var configSection = Substitute.For<IConfigurationSection>();
var configuration = Substitute.For<IConfiguration>();

configSetion.Get<ClientConfiguration>().Returns(new ClientConfiguration());

configuration.GetSection(Arg.Any<string>()).Returns(configSection);
Jean-François Beaulieu
  • 4,305
  • 22
  • 74
  • 107
  • 4
    Don't bother trying to mock that. A Configuration instance can be built with an in-memory provider to get the desired behavior. Reference https://stackoverflow.com/a/64795010/5233410 – Nkosi Dec 07 '21 at 18:20
  • This worked for me after managing to generate a Json string from my custom class. Thanks! – Jean-François Beaulieu Dec 11 '21 at 23:48

0 Answers0