c# - 在 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
解决方案
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");
推荐阅读
- typescript - 打字稿如何从常量属性值推断类型
- apache-spark - 为什么 Apache Spark 会根据文件大小读取 CSV 分区以及如何更改分区?
- elastic-stack - 如何微调 ELK
- angular - 谷歌地图在 Angular 中不起作用并给出 InvalidKeyMapError 错误
- python - 数字边界框 Opencv Python
- java - 如何将 jms 作为 json 格式 (SyndEntryImpl)
- airflow-scheduler - 重新处理 Airflow 的历史数据
- python - Pandas 数据类型在不使用 Try except 的情况下转换时捕获错误
- python - 在 php 中抓取受保护的电子邮件
- javascript - React native (Android) - 创建 URL.createObjectURL(blob)