【发布时间】:2022-10-15 21:12:46
【问题描述】:
我想使用 DefaultAzureCredential 和 Moq 框架模拟与 Azure 应用程序配置(功能标志)服务的连接。
我在 Program.cs 中使用它
public static WebApplicationBuilder UseFeatureFlags(this WebApplicationBuilder hostBuilder)
{
var endpoint = hostBuilder.Configuration.GetValue<string>("Azure:AppConfig:Endpoint");
var cacheExpirationInterval = hostBuilder.Configuration.GetValue<int>("FeatureManagement:CacheExpirationInterval");
var label = hostBuilder.Configuration.GetValue<string>("FeatureManagement:Label");
hostBuilder.Host
.ConfigureAppConfiguration((builder, config) =>
config.AddAzureAppConfiguration(options =>
options.Connect(new Uri(endpoint), new DefaultAzureCredential())
.UseFeatureFlags(featureFlagOptions =>
{
featureFlagOptions.CacheExpirationInterval = TimeSpan.FromMinutes(cacheExpirationInterval);
featureFlagOptions.Label = label;
})));
return hostBuilder;
}
现在我正在尝试修复我的单元测试,因为它们在我的 WebApplicationFactory(401 未授权)中失败了
options.Connect(new Uri(endpoint), new DefaultAzureCredential())
有没有简单的方法来模拟它?这是我的 Api WebApplicationFactory 的一部分
public class ApiWebApplicationFactory : WebApplicationFactory<Program>
{
public HttpClient WithMocks(
IMock<ISecretVault>? secretVaultMock = null,
IMock<IFeatureManager>? featureManager = null)
{
var client = WithWebHostBuilder(builder =>
builder.ConfigureServices(services =>
{
ReplaceWithMock(typeof(ISecretVault), secretVaultMock, services);
ReplaceWithMock(typeof(IFeatureManager), featureManager, services);
})).CreateClient();
return client;
}
private static void ReplaceWithMock<T>(Type tgt, IMock<T>? mock, IServiceCollection services)
where T : class
{
if (mock != null)
{
var serviceClientDescriptor = services.Single(d => d.ServiceType == tgt);
services.Remove(serviceClientDescriptor);
services.AddScoped(_ => mock.Object);
}
}
}
提前感谢您提供任何提示或示例代码
【问题讨论】:
标签: azure moq xunit azure-app-configuration azure-feature-manager