C# 如何模拟 Configuration.GetSection("foo:bar").Get&am

C# how to mock Configuration.GetSection(quot;foo:barquot;).Getlt;Listlt;stringgt;gt;()(C# 如何模拟 Configuration.GetSection(foo:bar).Getlt;Listlt;stringgt;gt;())
本文介绍了C# 如何模拟 Configuration.GetSection("foo:bar").Get<List<string>>()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在 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);

推荐答案

我遇到了同样的问题,发现我需要为数组中的每个元素以及数组节点本身创建一个mock 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);

附:我使用的是 Moq,所以请翻译成您选择的模拟库.

P.S. I'm using Moq, so please translate to your mock library of choice.

附言如果您对为什么最终会起作用、不可修改的 Get() 方法的作用或有比 OP 更复杂的场景感兴趣,阅读此类可能会有所帮助: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

这篇关于C# 如何模拟 Configuration.GetSection("foo:bar").Get&lt;List&lt;string&gt;&gt;()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)