编程语言
首页 > 编程语言> > c# – 如何设置IConfigurationRoot的模拟返回值

c# – 如何设置IConfigurationRoot的模拟返回值

作者:互联网

参见英文答案 > Expression references a method that does not belong to the mocked object                                    2个
我使用IConfigurationRoute来访问这样的目录.

if (type == "error") directory = _config.GetValue<string>("Directories:SomeDirectory");

_config是在构造函数中注入的IConfigurationRoot.

我尝试了以下方式来模拟它.

        var mockConfigurationRoot = new Mock<IConfigurationRoot>();
        mockConfigurationRoot.Setup(c => c.GetValue<string>("Directories: SomeDirectory"))
            .Returns("SomeDirectory")
            .Verifiable();
        var config = mockConfigurationRoot.Object;

问题是在运行测试时,Xunit会抛出异常说法

“System.NotSupportedException : Expression references a method that
does not belong to the mocked object”

我该如何解决这个问题?

解决方法:

我是使用SetupGet方法完成的,如下所示.它适用于我,希望它有所帮助.

_configurationRoot = new Mock<IConfigurationRoot>();
_configurationRoot.SetupGet(x => x[It.IsAny<string>()]).Returns("the string you want to return");

标签:c,unit-testing,moq,asp-net-core,xunit-net
来源: https://codeday.me/bug/20190712/1443309.html