首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何模拟IConfiguration.GetValue

如何模拟IConfiguration.GetValue
EN

Stack Overflow用户
提问于 2020-11-11 21:13:56
回答 9查看 53K关注 0票数 88

我试图模拟顶级(不属于任何部分)配置值(.NET Core的IConfiguration),但没有成功。例如,这两种方法都不起作用(使用NSubstitute,但对于Moq或我相信的任何模拟包来说都是一样的):

代码语言:javascript
运行
复制
var config = Substitute.For<IConfiguration>();
config.GetValue<string>(Arg.Any<string>()).Returns("TopLevelValue");
config.GetValue<string>("TopLevelKey").Should().Be("TopLevelValue"); // nope
// non generic overload
config.GetValue(typeof(string), Arg.Any<string>()).Returns("TopLevelValue");
config.GetValue(typeof(string), "TopLevelKey").Should().Be("TopLevelValue"); // nope

在我的例子中,我还需要从同一个配置实例调用GetSection

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2020-11-11 22:17:49

可以对内存中的数据使用实际的配置实例.

代码语言:javascript
运行
复制
//Arrange
var inMemorySettings = new Dictionary<string, string> {
    {"TopLevelKey", "TopLevelValue"},
    {"SectionName:SomeKey", "SectionValue"},
    //...populate as needed for the test
};

IConfiguration configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(inMemorySettings)
    .Build();


//...

现在的问题是按照需要使用配置来执行测试。

代码语言:javascript
运行
复制
//...

string value = configuration.GetValue<string>("TopLevelKey");

string sectionValue = configuration.GetSection("SectionName").GetValue<string>("SomeKey");

//...

参考资料:内存配置提供程序

票数 201
EN

Stack Overflow用户

发布于 2021-03-10 07:23:02

我不知道NSubstitute,但这是我们在Moq中可以做的。这两种情况都是一样的。

GetValue<T>()内部使用GetSection()

您可以模拟GetSection并返回您自己的IConfigurationSection

这包括两个步骤。

1)。为IConfigurationSection (mockSection)创建一个模拟&安装.Value属性以返回所需的配置值。

2)。模拟.GetSection on Mock< IConfiguration >,并返回上面的mockSection.Object

代码语言:javascript
运行
复制
Mock<IConfigurationSection> mockSection = new Mock<IConfigurationSection>();
mockSection.Setup(x=>x.Value).Returns("ConfigValue");

Mock<IConfiguration> mockConfig = new Mock<IConfiguration>();
mockConfig.Setup(x=>x.GetSection(It.Is<string>(k=>k=="ConfigKey"))).Returns(mockSection.Object);
票数 24
EN

Stack Overflow用户

发布于 2021-06-08 11:19:18

模拟IConfiguration

代码语言:javascript
运行
复制
Mock<IConfiguration> config = new Mock<IConfiguration>();

SetupGet

代码语言:javascript
运行
复制
config.SetupGet(x => x[It.Is<string>(s => s == "DeviceTelemetryContainer")]).Returns("testConatiner");
config.SetupGet(x => x[It.Is<string>(s => s == "ValidPowerStatus")]).Returns("On");
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64794219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档