Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock configuration.GetSection with FakeItEasy syntax?

I have the following appsettings.json configuration.

"SettingsConfig": [
{
  "Name": "Something",
  "Node": "Something",
  "SettingName": "Something"
},
{
  "Name": "Something",
  "Node": "Something",
  "SettingName": "Something"
}]

I want to write UnitTest ,but the following syntax does not work.

_configuration = A.Fake<IConfiguration>();
A.CallTo(() => _configuration.GetSection("SettingsConfig")).Returns(new List<SettingsConfig>());

Error message: IConfigurationSection does not contain definition for Returns.

How IConfiguration can be mocked with FakeItEasy syntax in order to apply mock data for UnitTesting?

like image 724
Sarah Avatar asked Dec 28 '25 17:12

Sarah


1 Answers

If you take a look at the return value of IConfiguration.GetSection(), you'll see that it expects to return an IConfigurationSection. That's the first issue here.

Beyond that, in order to pull out your List from the config, you would need to do something like

_configuration.GetSection("SettingsConfig").Get<List<SettingsConfig>>();

Unfortunately, the .Get<> method on an IConfigurationSection is an extension method, which cannot be faked by FakeItEasy. You will get the following error:

The current proxy generator can not intercept the method Microsoft.Extensions.Configuration.ConfigurationBinder.Get... - Extension methods can not be intercepted since they're static.

You'll need to put another interface in front of the IConfiguration that wraps the extension method if you need to test it.

Otherwise to fake your configuration file, you could do something like the following:

var fakeConfigSection = A.Fake<IConfigurationSection>();
A.CallTo(() => fakeConfigSection["Name"])
    .Returns("MyFakedConfigValue");

var fakeConfig = A.Fake<IConfiguration>();
A.CallTo(() => fakeConfig.GetSection("SettingsConfig"))
    .Returns(fakeConfigSection);
like image 173
Isaac Avatar answered Dec 30 '25 05:12

Isaac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!