2021-12-27 乐帮网
c# netcore
.NET Core或者.Net 6 中我们可以配置文件来添加值(appsetting.json),在写单元测试时我们怎么模拟这些值呢?比如以下一段代码:
[Fact]
public void Test_IsConfigured_Positive()
{
  // test against this configuration
  IConfiguration config = new ConfigurationBuilder()
    // how to populate it via code
    .Build();
  // the extension method to test
  Assert.True(config.IsConfigured());
}
在Builder完成后我想以这样的文件来构建
{
  "MySection": {
     // the existence of the section activates something triggering IsConfigured to be true but does not overwrite any default value
   }
 }
正确的答案是使用MemoryConfigurationBuilderExtensions 来做一个参数字典,代码如下:
using Microsoft.Extensions.Configuration;
var myConfiguration = new Dictionary<string, string>
{
    {"Key1", "Value1"},
    {"Nested:Key1", "NestedValue1"},
    {"Nested:Key2", "NestedValue2"}
};
var configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(myConfiguration)
    .Build();
它的值映射成json文件格式如下:
{
  "Key1": "Value1",
  "Nested": {
    "Key1": "NestedValue1",
    "Key2": "NestedValue2"
  }
}
或者还有以下有价值的写法:
var configuration = new Mock<IConfiguration>();
var configSection = new Mock<IConfigurationSection>();
configSection.Setup(x => x.Value).Returns("fake value");
configuration.Setup(x => x.GetSection("MySection")).Returns(configSection.Object);
//OR
configuration.Setup(x => x.GetSection("MySection:Value")).Returns(configSection.Object);
 
                        
                                关注我的微信公众号
                                在公众号里留言交流
                                投稿邮箱:1052839972@qq.com
                            
                        庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
                        雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。
                        
                    
 
                        
                                如果感觉对您有帮助
                                欢迎向作者提供捐赠
                                这将是创作的最大动力