C# how to mock Configuration.GetSection(“foo:bar”).Get>()

后端 未结 5 1712
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 06:35

I have a list like following in config.json file `

{
  \"foo\": {
    \"bar\": [
      \"1\",
      \"2\",
      \"3\"
    ]
  }
}`

I am ab

5条回答
  •  清歌不尽
    2021-01-04 06:55

    In general, if you have a key/value at the root level and you want to mock this piece of code:

    var threshold = _configuration.GetSection("RootLevelValue").Value;
    

    you can do:

    var mockIConfigurationSection = new Mock();
    mockIConfigurationSection.Setup(x => x.Key).Returns("RootLevelValue");
    mockIConfigurationSection.Setup(x => x.Value).Returns("0.15");
    _mockIConfiguration.Setup(x => x.GetSection("RootLevelValue")).Returns(mockIConfigurationSection.Object);
    

    If the key/value is not at the root level, and you want to mock a code that is like this one:

    var threshold = _configuration.GetSection("RootLevelValue:SecondLevel").Value;
    

    you have to mock Path as well:

    var mockIConfigurationSection = new Mock();
    mockIConfigurationSection.Setup(x => x.Path).Returns("RootLevelValue");
    mockIConfigurationSection.Setup(x => x.Key).Returns("SecondLevel");
    mockIConfigurationSection.Setup(x => x.Value).Returns("0.15");
    

    and so on for the third level:

    var threshold = _configuration.GetSection("RootLevelValue:SecondLevel:ThirdLevel").Value;
    

    you have to mock Path as well:

    var mockIConfigurationSection = new Mock();
    mockIConfigurationSection.Setup(x => x.Path).Returns("RootLevelValue:SecondLevel");
    mockIConfigurationSection.Setup(x => x.Key).Returns("ThirdLevel");
    mockIConfigurationSection.Setup(x => x.Value).Returns("0.15");
    

提交回复
热议问题