在 Azure Devops 管道中使用 Cosmos Db 进行单元测试失败

时间:2021-06-30 06:58:43

标签: c# azure-devops xunit azure-cosmosdb-emulator

我编写了单元测试用例,其中我的测试用例是针对 Cosmos Db 模拟器编写的。 (不知道模拟器是什么的人,它是微软提供的本地开发cosmos Db,一般用来测试你的查询)

在我的单元测试用例中,我正在实例化 Emulator 数据库,然后运行测试用例。当我将此更改推送到 Azure DevOps 管道时,会出现问题。那里的测试用例失败,错误为

<块引用>

目标机器主动拒绝连接。

这确实意味着它无法实例化数据库。我怎样才能解决这个问题。有什么想法吗??

这里是测试的初始代码

public class CosmosDataFixture : IDisposable
{
        public static readonly string CosmosEndpoint = "https://localhost:8081";
        public static readonly string EmulatorKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        public static readonly string DatabaseId = "testdb";
        public static readonly string RecordingCollection = "testcolec";
        public static string Root = Directory.GetParent( Directory.GetCurrentDirectory() ).Parent.Parent.FullName;
        public static DocumentClient client { get; set; }
public async Task ReadConfigAsync()
        {

          //  StartEmulatorDatabaseFromPowerShell();
            client = new DocumentClient( new Uri( CosmosEndpoint ), EmulatorKey,
                 new ConnectionPolicy
                 {
                     ConnectionMode = ConnectionMode.Direct,
                     ConnectionProtocol = Protocol.Tcp

                 } );
            await client.CreateDatabaseIfNotExistsAsync( new Database { Id = DatabaseId } );
            await client.CreateDocumentCollectionIfNotExistsAsync( UriFactory.CreateDatabaseUri( DatabaseId ),
                new DocumentCollection { Id = RecordingCollection } );
            await ReadAllData( client );
        }
     public CosmosDataFixture()
        {
                      
            ReadConfigAsync();     
        }


        public void Dispose()
        {
          DeleteDatabaseFromPowerShell();// this is also defined in above class
        }
    }   
    public class CosmosDataTests : IClassFixture<CosmosDataFixture>
    { // mu unit test case goes here

1 个答案:

答案 0 :(得分:0)

您需要将此语句添加到您的 yaml 管道中:

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"
      Start-CosmosDbEmulator    

CosmosDB 的连接字符串应该是:AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==

您可以像这样实例化 CosmosDB 客户端:

var connectionString = "AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
var client = new CosmosClient(connectionString);
var database = client.CreateDatabaseIfNotExistsAsync("testdb");
var container = await database.Database.CreateContainerIfNotExistsAsync("testcolec", "/partitionKey");