問題描述
我在 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);
推薦答案
我遇到了同樣的問題,發(fā)現(xiàn)我需要為數(shù)組中的每個元素以及數(shù)組節(jié)點本身創(chuàng)建一個mock IConfigurationSection,然后設(shè)置父節(jié)點返回子節(jié)點,子節(jié)點返回它們的值.在 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);
附:我使用的是 Moq,所以請翻譯成您選擇的模擬庫.
P.S. I'm using Moq, so please translate to your mock library of choice.
附言如果您對為什么最終會起作用、不可修改的 Get() 方法的作用或有比 OP 更復(fù)雜的場景感興趣,閱讀此類可能會有所幫助:https://github.com/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: https://github.com/aspnet/Extensions/blob/release/2.1/src/Configuration/Config.Binder/src/ConfigurationBinder.cs
這篇關(guān)于C# 如何模擬 Configuration.GetSection("foo:bar").Get<List<string>>()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!