【发布时间】:2021-04-30 18:02:43
【问题描述】:
TL;DR
我使用来自第 3 方库的枚举,我想进行一些测试来检查这些枚举的值是否与我在位于主 Web api 项目中的 dictionaries.postmarks.json 文件中的值一致。
有什么方法可以在不将dictionaries.postmarks.json 文件复制到测试项目的情况下实现这一点?
详情:
dictionaries.postmarks.json 包含一些密钥对:
{
"PostMarks": [
{
"Code": 0,
"Name": "Simple"
},
{
"Code": 1,
"Name": "Complex"
},
{
"Code": 2,
"Name": "Any"
},
. . .
]
}
在ConfigureServices我注册选项如下:
var dictionariesConfiguration = new ConfigurationBuilder()
.SetBasePath(HostEnvironment.ContentRootPath)
.AddJsonFile("dictionaries.postmarks.json", false, true)
.Build();
services.Configure<DictionaryOptions>(dictionariesConfiguration);
就是这样。从那以后,我可以非常完美地在我的服务中使用IOptions<DictionaryOptions>。
现在我有一个单独的测试项目,我想在其中检查第 3 方 PostMark 枚举的值是否与我在 dictionaries.postmarks.json 文件中的值完全相同。
我不想将 json 文件复制到我的测试项目 (proposed here),因为我想测试完全存在于我的 web api 项目中的值。
这就是我到目前为止所做的:
public class EnumTests
{
private readonly IConfiguration _configuration;
public EnumTests()
{
_configuration = InitConfiguration();
}
private IConfiguration InitConfiguration()
{
//var dir = should I hard code dir here?
return new ConfigurationBuilder()
.SetBasePath(dir)
.AddJsonFile("dictionaries.postmarks.json")
.Build();
}
[Fact]
public void PostMarkEnum_ShouldBeEqualToPostMarksOptions()
{
var fromOptions = _configuration.GetSection("PostMarks").Get<List<DictionaryElement>>();
var fromLibrary = Enum.GetValues(typeof(PostMark)).Cast<long>().ToList();
bool equal = true;
for (var i = 0; i < fromOptions.Count; i++)
{
if (fromOptions[i].Code != fromLibrary[i])
{
equal = false;
break;
}
}
Assert.True(equal);
}
}
public class DictionaryElement
{
public long Code { get; set; }
public string Name { get; set; }
}
顺便说一句,我有一些使用WebApplicationFactory 的集成测试,所以我可以从中读取配置,但don't know 是否可能。
【问题讨论】:
标签: c# asp.net-core integration-testing .net-5