C# 如何模拟 Configuration.GetSection ("foo:bar").Get<List<string>>()

标签 c# unit-testing mocking moq

我在 config.json 文件中有如下列表 `

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

我可以在运行时使用

获取列表
Configuration.GetSection("foo:bar").Get<List<string>>()

我想模拟 configuration.GetSection 来编写单元测试。

以下语法失败

mockConfigRepo
    .SetupGet(x => x.GetSection("reportLanguageSettings:reportLanguageList").Get<List<string>>())
    .Returns(reportLanguages);

最佳答案

我能够使用 ConfigurationBuilder 解决它。希望这会有所帮助

  var appSettings = @"{""AppSettings"":{
            ""Key1"" : ""Value1"",
            ""Key2"" : ""Value2"",
            ""Key3"" : ""Value3""
            }}";

  var builder = new ConfigurationBuilder();

  builder.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(appSettings)));

  var configuration= builder.Build();

关于C# 如何模拟 Configuration.GetSection ("foo:bar").Get<List<string>>(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201588/

相关文章:

c# - Windows Vista : Unable to load DLL 'x.dll' : Invalid access to memory location. (DllNotFoundException)

C#8.0 switch 语句和局部变量

c# - 你如何使用 Moq 来模拟一个简单的界面?

objective-c - 模拟 CLLocationManager (swift) 用于测试

c# - 手动使用真正的 resx 解析 IStringLocalizer

c# - UC 中的派生类给出 "type exist in both dlls"错误

c++ - 使用 C++ Builder 可以替代 DUnit 吗?

python - 如何模拟 python (flask) webapp 中的服务层进行单元测试?

firebase - 有没有办法对于Jest的方式模拟 firebase 模块?

vb.net - 如何在 VB.NET 中使用 Rhino Mocks 模拟方法(自定义行为)