.net core 2.0测试 - 如何在测试项目中存储设置?

时间:2017-10-25 16:44:43

标签: c# testing .net-core azure-devops

我需要在.NET Core 2.0集成测试中存储连接字符串和其他设置(因此,它是一个测试项目,使用xUnit)。考虑到本地和VSTS中运行的测试,我该如何安全地做到这一点?理想情况下,我需要将这些设置分开用于本地环境并在VSTS上运行。

1 个答案:

答案 0 :(得分:0)

您可以添加多个配置文件,例如 appsettings.json,appsettings.dev.json,appsettings.test.json ,然后为相关环境设置 dev 值变量并为构建的相关变量设置 test 值。

之后,通过Token Replace任务

替换 appsettings.test.json 文件中的值

简单步骤:

  1. Microsoft.Extensions.Configuration.Json package安装到xUnit测试项目
  2. appsettings.json,appsettings.dev.json和appsettings.test.json 配置文件添加到项目中
  3. 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"
      }
    }
    
    1. 将这些文件的复制设置为输出目录属性如果更新则复制。 4:简单的测试代码
    2.             [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);
                  }
      
      1. 添加 ASPNETCORE_ENVIRONMENT (值:测试), testDev testName 变量来构建定义,您可以点击锁定图标将变量类型更改为机密
      2. 在构建任务之前添加替换令牌任务(目标文件:**\appsettings.test.json