Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup Mock of IConfigurationRoot to return value [duplicate]

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?

like image 970
Virodh Avatar asked Apr 25 '17 18:04

Virodh


People also ask

Can we mock IConfiguration?

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.

What is IConfigurationRoot?

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 .


1 Answers

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"); 
like image 96
user3130628 Avatar answered Oct 14 '22 02:10

user3130628