在 .Net Core xUnit test 项目中使用配置文件

在对项目做集成测试的时候,经常会需要用到一些参数比如用户名密码等,这些参数不宜放在测试代码中。本文介绍一种方法:使用配置文件。

添加配置文件

在集成测试项目目录下新建文件:Configuration.json,并配置好需要的参数

{
    "SendCloudId": "id",
    "SendCloudKey": "key"
}

配置工程文件,添加配置文件到输出

<ItemGroup>
<None Update="Configuration.json">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

添加解析配置文件依赖包

使用Nuget Package Manager,添加依赖包:Microsoft.Extensions.Configuration.Json

然后使用 dotnet restore,加载依赖包

加载配置

var config = new ConfigurationBuilder()
    .AddJsonFile("Configuration.json")
    .Build();

var credential = new Credential()
{
    Id = config["SendCloudId"],
    Key = config["SendCloudKey"]
};
原文地址:https://www.cnblogs.com/windchen/p/7191290.html