I have used IConfigurationRoute to access a directory like this.
if (type == "error") directory = _config.GetValue<string>("Directories:SomeDirectory");
_config is IConfigurationRoot injected in the constructor.
I tried the following way to mock it.
var mockConfigurationRoot = new Mock<IConfigurationRoot>(); mockConfigurationRoot.Setup(c => c.GetValue<string>("Directories: SomeDirectory")) .Returns("SomeDirectory") .Verifiable(); var config = mockConfigurationRoot.Object;
The issue is while running the test Xunit throws the exception saying
"System.NotSupportedException : Expression references a method that does not belong to the mocked object"
How can I solve this issue?
You can see from the code snippet from above that GetValue<T> uses GetValue which down the line is calling GetSection. Method GetSection is declared in IConfiguration which means you can mock it, and by mocking it you also mock GetValue<T> as it is wrapping GetSection indirectly through GetValue.
ASP.NET Core in Action ConfigurationBuilder describes how to construct the final configuration representation for your app, and IConfigurationRoot holds the configuration values themselves. You describe your configuration setup by adding a number of IConfigurationProviders to IConfigurationBuilder .
I did it using the SetupGet method as follows. It works for me, hope it helps.
_configurationRoot = new Mock<IConfigurationRoot>(); _configurationRoot.SetupGet(x => x[It.IsAny<string>()]).Returns("the string you want to return");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With