我试图模拟顶级(不属于任何部分)配置值(.NET Core的IConfiguration),但没有成功。例如,这两种方法都不起作用(使用NSubstitute,但对于Moq或我相信的任何模拟包来说都是一样的):
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
。
发布于 2020-11-11 22:17:49
可以对内存中的数据使用实际的配置实例.
//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();
//...
现在的问题是按照需要使用配置来执行测试。
//...
string value = configuration.GetValue<string>("TopLevelKey");
string sectionValue = configuration.GetSection("SectionName").GetValue<string>("SomeKey");
//...
参考资料:内存配置提供程序
发布于 2021-03-10 07:23:02
我不知道NSubstitute,但这是我们在Moq中可以做的。这两种情况都是一样的。
GetValue<T>()
内部使用GetSection()
。
您可以模拟GetSection
并返回您自己的IConfigurationSection
。
这包括两个步骤。
1)。为IConfigurationSection
(mockSection)创建一个模拟&安装.Value
属性以返回所需的配置值。
2)。模拟.GetSection
on Mock< IConfiguration >,并返回上面的mockSection.Object
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);
发布于 2021-06-08 11:19:18
模拟IConfiguration
Mock<IConfiguration> config = new Mock<IConfiguration>();
SetupGet
config.SetupGet(x => x[It.Is<string>(s => s == "DeviceTelemetryContainer")]).Returns("testConatiner");
config.SetupGet(x => x[It.Is<string>(s => s == "ValidPowerStatus")]).Returns("On");
https://stackoverflow.com/questions/64794219
复制相似问题