我需要在.NET Core 2.0集成测试中存储连接字符串和其他设置(因此,它是一个测试项目,使用xUnit)。考虑到本地和VSTS中运行的测试,我该如何安全地做到这一点?理想情况下,我需要将这些设置分开用于本地环境并在VSTS上运行。
答案 0 :(得分:0)
您可以添加多个配置文件,例如 appsettings.json,appsettings.dev.json,appsettings.test.json ,然后为相关环境设置 dev 值变量并为构建的相关变量设置 test 值。
之后,通过Token Replace任务
替换 appsettings.test.json 文件中的值简单步骤:
appsettings.json:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
"OtherSettings": {
"UserName": "name1",
"Pass": "pass1"
}
}
appsettings.dev.json:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=dev;Trusted_Connection=True;"
},
"OtherSettings": {
"UserName": "devname1",
"Pass": "pass1"
}
}
appsettings.test.json:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=#{testDev}#;Trusted_Connection=True;"
},
"OtherSettings": {
"UserName": "#{testName}#",
"Pass": "pass1"
}
}
[Fact]
public void Test1()
{
var envVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
Console.WriteLine($"env: {envVariable}");
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{envVariable}.json", optional: true)
.Build();
var conn = config.GetConnectionString("BloggingDatabase");
var otherSettings = config["OtherSettings:UserName"];
Console.WriteLine(conn);
Console.WriteLine(otherSettings);
}
**\appsettings.test.json
)