Mock IConfiguration
现在我们的程序需要读取配置信息基本上都是用IConfiguration 使用到的包有 Microsoft.Extensions.Configuration 和Microsoft.Extensions.Configuration.Binder
下面的代码可以直接从Dictionary这边来构建我们需要的IConfiguration
csharp
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;
}1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
完整的代码如下
csharp
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; }
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
上面的dictionary实际上相当于 在配置文件这边写了一个如下的配置节。
json
{
"Malema": {
"MaxReqeust": 56,
"ThirdApi": "https://www.malema.net/ip"
}
}1
2
3
4
5
6
2
3
4
5
6
使用Moq来Mock的话会更麻烦。推荐上面的这种方式。
