我想模拟使用DefaultAzureCredential和Moq框架连接到Azure (特性标志)服务。
我编写了基于Microsoft教程https://learn.microsoft.com/en-us/azure/azure-app-configuration/quickstart-feature-flag-aspnet-core?tabs=core6x%2Ccore5x的扩展。
我正在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);
}
}
}
谢谢您提供的任何提示或示例代码
发布于 2022-10-15 13:12:46
通常,在模拟时,您是在开发或单元测试中。
因此,我们发现最简单的选择是在开发或测试中简单地不使用Azure App,因为这违反了没有外部依赖的规则。AAC只是将值注入ConfigurationBuilder的包装器。所以,实际上,它在单元测试和开发中没有意义。
只有在UAT、分期和生产时,才能从AAC IMO读取设置。
不要嘲笑,不要用
https://stackoverflow.com/questions/73194162
复制相似问题