首页 > 解决方案 > 在 Azure Devops 管道中使用 Cosmos Db 进行单元测试失败

问题描述

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

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

目标机器主动拒绝连接。

这确实意味着它无法实例化 db。我怎样才能解决这个问题。任何想法??

这是测试的初始代码

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

标签: c#azure-devopsxunitazure-cosmosdb-emulator

解决方案


You need to add this statement to your yaml Pipeline:

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

And the Connection String for CosmosDB should be: AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==

You can instantiate the CosmosDB client like that:

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");


推荐阅读