由程式指定 IConfiguration 設定值測試 ASP.NET Core 服務
| | 0 | | 2,337 |
假設我在 ASP.NET Core 有個服務 CopyService,建構式接收 IConfiguration 從中讀取設定值,appsettings.json 格式如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"CodeName": "Test",
"Folders": [
{
"Name": "Folder1",
"Path": "D:\\Folder1",
"ExcludePaths": [
"File1",
"File2"
]
},
{
"Name": "Folder2",
"Path": "D:\\Folder2"
}
]
}
CopyService 使用 _config["CodeName"] 讀取 CodeName,並使用 GetSection("Folders").Get<List<FolderSetting>>() 對映成 FolderSetting 物件集合:
public class CopyService
{
IConfiguration _config;
public CopyService(IConfiguration config)
{
_config = config;
}
public string DebugInfo =>
_config["CodeName"] + "\n" +
string.Join("\n",
_config.GetSection("Folders").Get<List<FolderSetting>>()
.Select(x => $"{x.Name}/{x.Path}/{x.ExcludePaths}").ToArray());
}
public class FolderSetting {
public string Name {get; set;}
public string Path {get; set;}
public string ExcludePaths {get; set;}
}
這段程式配合 appsettings.json 可以順利運作,但有沒有可能不產生 appsettings.json,在程式裡捏造一組設定值做測試呢?
.NET 設想周到,什麼怪兵器都有,Memory Configuration Provider 支援用 Dictionary<string, string> 存放設定值,可以滿足我們的需求。
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string> {
["CodeName"] = "TEST",
["Folders:0:Name"] = "Folder1",
["Folders:0:Path"] = "X:\\Folder1",
["Folders:0:ExcludePaths"] = "data.json",
["Folders:1:Name"] = "Folder2",
["Folders:1:Path"] = "X:\\Folder2"
}).Build();
var copyService = new CopyService(config);
Console.WriteLine(copyService.DebugInfo);
使用 "Folder:0:Name" 表示法,連 List<FolderSetting> 都能模擬,讚!
Example of using Dictionary as IConfiguration provider ASP.NET Core.
Comments
Be the first to post a comment