How to setup Mock of IConfigurationRoot to return value

Virodh picture Virodh · Apr 25, 2017 · Viewed 30.2k times · Source

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?

Answer

user3130628 picture user3130628 · Nov 28, 2017

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");