我在config.json文件中有一个如下列表`
I have a list like following in config.json file `
{ "foo": { "bar": [ "1", "2", "3" ] } }`我可以使用
Configuration.GetSection("foo:bar").Get<List<string>>()我想模拟 configuration.GetSection 来编写单元测试.
I want to mock the configuration.GetSection to write unit test.
以下语法失败
mockConfigRepo .SetupGet(x => x.GetSection("reportLanguageSettings:reportLanguageList").Get<List<string>>()) .Returns(reportLanguages); 推荐答案我遇到了相同的问题,发现我需要为数组中的每个元素以及数组节点本身创建一个模拟IConfigurationSection,然后设置父节点以返回子代,子代返回其值.在OP示例中,它看起来像这样:
I've encountered same issue and found that I needed to create a mock IConfigurationSection for every element in the array, as well as the array node itself, and then setup the parent node to return children, and children to return their values. In OP example, it would look like this:
var oneSectionMock = new Mock<IConfigurationSection>(); oneSectionMock.Setup(s => s.Value).Returns("1"); var twoSectionMock = new Mock<IConfigurationSection>(); twoSectionMock.Setup(s => s.Value).Returns("2"); var fooBarSectionMock = new Mock<IConfigurationSection>(); fooBarSectionMock.Setup(s => s.GetChildren()).Returns(new List<IConfigurationSection> { oneSectionMock.Object, twoSectionMock.Object }); _configurationMock.Setup(c => c.GetSection("foo:bar")).Returns(fooBarSectionMock.Object);P.S.我正在使用Moq,因此请转换为您选择的模拟库.
P.S. I'm using Moq, so please translate to your mock library of choice.
P.P.S.如果您对为什么这种方法最终有用,无法模拟的Get()方法做什么或比OP具有更复杂的方案感兴趣,那么阅读此类可能会有所帮助: github/aspnet/Extensions/blob/release/2.1/src/Configuration/Config.Binder/src/ConfigurationBinder.cs
P.P.S. If you are interested in why this ends up working, what unmockable Get() method does, or have a more complex scenario than OP, reading this class may be helpful: github/aspnet/Extensions/blob/release/2.1/src/Configuration/Config.Binder/src/ConfigurationBinder.cs
更多推荐
C#如何模拟Configuration.GetSection("foo:bar").Get< List< str
发布评论