如何将IConfigurationRoot的Mock设置为返回值 [英] How to setup Mock of IConfigurationRoot to return value

查看:252
本文介绍了如何将IConfigurationRoot的Mock设置为返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用IConfigurationRoute访问这样的目录.

I have used IConfigurationRoute to access a directory like this.

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

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

_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;

问题是在运行测试Xunit时抛出异常

The issue is while running the test Xunit throws the exception saying

"System.NotSupportedException:表达式引用一个方法,该方法可以 不属于模拟对象"

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

我该如何解决这个问题?

How can I solve this issue?

推荐答案

我使用SetupGet方法按如下进行操作.它对我有用,希望对您有帮助.

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

这篇关于如何将IConfigurationRoot的Mock设置为返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆