【发布时间】:2019-01-30 14:16:31
【问题描述】:
我正在尝试为以下内容编写单元测试:
[TestMethod]
public void GetInviteEndPoint_ShouldAccessAppSettings()
{
//Data pulled from the appsettings.test.json
var config = InitConfiguration();
var inviteEndPointConfig = config["InviteEndPoint"]; // <-- Pain Point
//Arrange Test && Mock if needed
string mockInviteEndPoint = "https://graph.microsoft.com/v1.0/invitations";
//Actual Code from Application (ACT)
SendInvite sendInvite = new SendInvite();
string inviteEndPoint = sendInvite.GetInviteEndPoint(config);
//Assert
// Assert always tests (Expected[Arranged], Actual[From Code Base])
Assert.AreEqual(mockInviteEndPoint, inviteEndPoint);
}
我的 appsettings.json 和 appsettings.test.json 看起来都一样。我很难从 .json 文件中获取值。我想知道是否有人可以对我坚持的这段代码提供任何见解。
{
"SendeInvite": {
"InviteEndPoint": "https://graph.microsoft.com/v1.0/invitations"
...Code Omitted...
}
}
我是不是打错了config["InvitedEndPoint"]?
请注意,我在测试类的顶部有以下代码
public static IConfiguration InitConfiguration()
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.test.json")
.Build();
return config;
}
【问题讨论】:
-
有什么问题?你得到一个例外,是
inviteEndPointConfignull?您确定正在加载正确的文件吗?"appsettings.test.json"是一个 relative 路径,这意味着测试运行程序将在 its 工作目录中查找它。即使那是bin/Debug,您也需要确保将appsettings.test.json复制到bin/debug -
您标记了您的问题 nunit,但根据您对 TestMethodAttribute 的使用,它显然使用了 Microsoft 的测试框架。请重新标记。