Mock IConfiguration

现在我们的程序需要读取配置信息基本上都是用IConfiguration 使用到的包有 Microsoft.Extensions.ConfigurationMicrosoft.Extensions.Configuration.Binder

下面的代码可以直接从Dictionary这边来构建我们需要的IConfiguration

private static IConfiguration GetARealConfiguration(Dictionary<string,string> dict)
{
    var data = new List<KeyValuePair<string, string>>();
    foreach (var item in dict)
    {
        data.Add(new KeyValuePair<string, string>(item.Key, item.Value));
    }
    var configuration = new ConfigurationBuilder().AddInMemoryCollection(data).Build();
    return configuration;
}

完整的代码如下

using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using Xunit;

namespace MyFirstUnitTests
{
    public class IConfigurationTest
    {
        [Fact]
        public void GetMalemaConfig_Should_Return_Correctly()
        {
            var dict = new Dictionary<string, string>
            {
                ["Malema:MaxRequest"] = "56",
                ["Malema:ThirdApi"] = "https://www.malema.net/ip"
            };
            var configuration = GetARealConfiguration(dict);
            var config = configuration.GetSection("malema").Get<MalemaConfig>();
            Assert.Equal(56, config.MaxRequest);
            Assert.Equal("https://www.malema.net/ip", config.ThirdApi);
        }

        private static IConfiguration GetARealConfiguration(Dictionary<string, string> dict)
        {
            var data = new List<KeyValuePair<string, string>>();
            foreach (var item in dict)
            {
                data.Add(new KeyValuePair<string, string>(item.Key, item.Value));
            }
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(data).Build();
            return configuration;
        }
    }

    public class MalemaConfig
    {
        public int MaxRequest { get; set; }

        public string ThirdApi { get; set; }
    }
}

上面的dictionary实际上相当于 在配置文件这边写了一个如下的配置节。

{
    "Malema": {
        "MaxReqeust": 56,
        "ThirdApi": "https://www.malema.net/ip"
    }
}

使用Moq来Mock的话会更麻烦。推荐上面的这种方式。

上一篇:Mock Ilogger
下一篇:Mock HttpRequest
最近更新的
...