gpt4 book ai didi

c# - 如何在Azure Function上执行基于xUnit的集成测试?

转载 作者:行者123 更新时间:2023-12-03 06:47:55 25 4
gpt4 key购买 nike

我不知道如何为 Azure Function 设置基于 xUnit 的集成测试。我有基于 .NET 6.0 的 Azure 函数 CreateObject。我想对这个功能进行一次集成测试。该函数使用以下外部组件:

  1. Azure Redis 缓存
  2. Azure CosmosDb
  3. Azure 服务总线
  4. 用于设置的 REST 服务
  5. 应用设置
  6. Serilog

CreateObject.cs

这是 Azure 函数。

public class CreateObject
{
private readonly ICreateObjectWorkflow _workflow;

public CreateObject(ICreateObjectWorkflow workflow)
{
_workflow = workflow;
}

[Function("CreateObject")]
public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
{
var input = new Dictionary<string, object>
{
["Body"] = await req.GetBody()
};

var output = await _workflow.Run(input);

var response = req.CreateResponse(HttpStatusCode.OK);

await response.WriteAsJsonAsync(output);

return response;
}
}

Startup.cs

这是 Azure Function 的启动,它会初始化许多服务。

namespace Get.Caa.IntegrationsApp.Starup;

public class Startup
{
public Task Run()
{
var environment = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT")!;
var fileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
string dirPath = fileInfo.Directory!.FullName;
var path = @$"{dirPath}/Appsettings/";

return Run(environment, path);
}

public Task Run(string environment, string path)
{
HealthServiceConfiguration healthOptions;
var host = new HostBuilder()
.ConfigureAppConfiguration(builder =>
{
builder
.SetBasePath(path)
.AddJsonFile(Path.Combine(path, $"appsettings.json"), optional: false, reloadOnChange: false)
.AddJsonFile(Path.Combine(path, $"appsettings.{environment}.json"), optional: false, reloadOnChange: false)
.AddJsonFile(Path.Combine(path, $"appsettings.{environment}.Health.json"), optional: false, reloadOnChange: false)
.AddJsonFile(Path.Combine(path, $"appsettings.{environment}.AzureApp.json"), optional: false, reloadOnChange: false)
.AddEnvironmentVariables();

var config = builder.Build();
})
.ConfigureFunctionsWorkerDefaults(worker =>
{
worker.UseNewtonsoftJson();
worker.UseMiddleware<ExceptionLoggingMiddleware>();

})
.ConfigureOpenApi()
.UseSerilogLogging()
.RegisterToHealthService()

.ConfigureServices(s =>
{
s.AddAppSettingsOption<AppSettings>();
s.AddAppSettingsOption<AzureIntegrationsAppSettingsConfiguration>();
s.AddAppSettingsOption<HealthServiceConfiguration>("HealthServiceConfiguration");
var serviceProvider = s.BuildServiceProvider();
var options = serviceProvider.GetRequiredService<IOptions<AppSettings>>().Value;
healthOptions = serviceProvider.GetRequiredService<IOptions<HealthServiceConfiguration>>().Value;
s.AddIntegrationApp($"{healthOptions.ServiceInfo.ApplicationUrl}/api");
healthOptions.AddEnvironmentVariables();
s.AddRedisCache(options);
s.AddHealthCheck(options, healthOptions);
s.AddAzureServiceBus(options.ServiceBusConnectionString);
s.AddSignalRService();
s.AddSingleton<INoSqlDatabase>(new CosmosNoSqlDatabase(options.CosmosDbEndpoint, options.CosmosDbPrimaryKey, options.DatabaseName));
s.AddIntegrationAppLifeCycle();
s.AddSerilog();
})
.Build();

return host.RunAsync();
}
}

我尝试使用以下类设置集成测试,但出现异常。

这是我运行集成测试时遇到的异常。

Get.Caa.IntegrationsApp.Test.Integration.CreateObjectWorkflowTests.CreateObjectWorkflowTests.ValidBody_ReturnCompleteNa
 Source: CreateObjectWorkflowTests.cs line 37

Test has multiple result outcomes
 2 Failed

Results

1)   Get.Caa.IntegrationsApp.Test.Integration.CreateObjectWorkflowTests.CreateObjectWorkflowTests.ValidBody_ReturnCompleteNa(data: [[[...]], [[...]], [[...]], [[...]], [[...]], ...], result: []) 
Duration: 1 ms

Message: 
System.InvalidOperationException : The gRPC channel URI 'http://:63530' could not be parsed.

Stack Trace: 
<>c.<AddGrpc>b__1_1(IServiceProvider p) line 61
CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
<4 more frames...>
CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
ServiceProvider.CreateServiceAccessor(Type serviceType)
ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
ServiceProvider.GetService(Type serviceType)
ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
Host.StartAsync(CancellationToken cancellationToken)
WebFixture.InitializeAsync() line 63

 Open result log

2)   Get.Caa.IntegrationsApp.Test.Integration.CreateObjectWorkflowTests.CreateObjectWorkflowTests.ValidBody_ReturnCompleteNa 
Duration: 1 ms

Message: 
[Test Collection Cleanup Failure (InMemory Web collection)]: System.NullReferenceException : Object reference not set to an instance of an object.

Stack Trace: 
WebFixture.DisposeAsync() line 70

 Open test log

ICreateObjectWorkflowClient.cs

我不确定是否必须使用 Refit 来调用 Azure 函数?

using Refit;
namespace Get.Caa.IntegrationsApp.Test.Integration.Clients;

public interface ICreateObjectWorkflowClient
{
[Post("/api/CreateObject/")]
Task<object> Run(Dictionary<string, object> input);
}

CreateObjectWorkflowTests.cs

我不确定是否必须使用 _httpClient 进行集成测试?

[Collection(WebCollection.Collection)]
[Trait("Category", "Integration")]
public class CreateObjectWorkflowTests
{
private readonly ICreateObjectWorkflowClient _httpClient;

public CreateObjectWorkflowTests(WebFixture fixture)
{
_httpClient = RestService.For<ICreateObjectWorkflowClient>(fixture.Client, new RefitSettings
{
ContentSerializer = new NewtonsoftJsonContentSerializer(
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
})
});
}


[Theory]
[JsonFileData(@".\Integration\CreateObjectWorkflowTests\Data\Customer.json", typeof(JObject), typeof(JObject))]
public async Task ValidBody_ReturnCompleteNa(JObject data, JObject result)
{
// Arrange
var entityList = data["entityList"]!;

// Act
var input = new Dictionary<string, object> { { "Body", entityList.ToString() } };
var output = await _httpClient.Run(input) as List<Response>;

// Assert
Assert.Single(output!);
Assert.Equal("Na", output![0].Completed);
Assert.Equal(0, output![0].Errors.Count);
Assert.Equal(1, output![0].Ids.Count);
Assert.Null(output![0].ResponseStatus);
Assert.Equal(result, result);
}
}

WebCollection.cs

我不确定是否必须使用 IAsyncLifetime 进行集成测试?


namespace Get.Caa.IntegrationsApp.Test.Integration.Fixtures;

[CollectionDefinition(Collection)]
public class WebCollection : ICollectionFixture<WebFixture>
{
public const string Collection = "InMemory Web collection";
}

public class WebFixture : IAsyncLifetime
{
internal IHost Host;
internal IServiceProvider ServiceProvider;
internal HttpClient Client;

public async Task InitializeAsync()
{
var environment = "Test";
var fileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
string dirPath = fileInfo.Directory!.FullName;
var path = @$"{dirPath}/Appsettings/";

path = @"D:\AzureIntegrationsApp\bin\Debug\net6.0\Appsettings\";

Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
.ConfigureAppConfiguration(builder =>
{
builder
.SetBasePath(path)
.AddJsonFile(Path.Combine(path, $"appsettings.json"), optional: false, reloadOnChange: false)
.AddJsonFile(Path.Combine(path, $"appsettings.{environment}.json"), optional: false, reloadOnChange: false)
.AddJsonFile(Path.Combine(path, $"appsettings.{environment}.Health.json"), optional: false, reloadOnChange: false)
.AddJsonFile(Path.Combine(path, $"appsettings.{environment}.AzureApp.json"), optional: false, reloadOnChange: false)
.AddEnvironmentVariables();

var config = builder.Build();
})
.ConfigureFunctionsWorkerDefaults(worker =>
{
worker.UseNewtonsoftJson();
worker.UseMiddleware<ExceptionLoggingMiddleware>();

})
.ConfigureWebHostDefaults(x =>
{
x.UseTestServer();
x.UseStartup<Internal.Startup>();
}).Build();

await Host.StartAsync();
ServiceProvider = Host.Services;
Client = Host.GetTestClient();
}

public async Task DisposeAsync()
{
Client.Dispose();
await Host.StopAsync();
Host.Dispose();
}
}

Startup.cs

我不确定是否必须使用自定义启动进行集成测试?


namespace Get.Caa.IntegrationsApp.Test.Integration.Internal
{
internal class Startup
{
public Startup(IConfiguration configuration) => Configuration = configuration;

private IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection s)
{
s.AddAppSettingsOption<AppSettings>();
s.AddAppSettingsOption<AzureIntegrationsAppSettingsConfiguration>();
s.AddAppSettingsOption<HealthServiceConfiguration>("HealthServiceConfiguration");

var serviceProvider = s.BuildServiceProvider();
var options = serviceProvider.GetRequiredService<IOptions<AppSettings>>().Value;

//var healthOptions = serviceProvider.GetRequiredService<IOptions<HealthServiceConfiguration>>().Value;
//s.AddIntegrationApp($"{healthOptions.ServiceInfo.ApplicationUrl}/api");
//healthOptions.AddEnvironmentVariables();
//s.AddHealthCheck(options, healthOptions);

s.AddRedisCache(options);
s.AddAzureServiceBus(options.ServiceBusConnectionString);
s.AddSignalRService();
s.AddSingleton<INoSqlDatabase>(new CosmosNoSqlDatabase(options.CosmosDbEndpoint, options.CosmosDbPrimaryKey, options.DatabaseName));
s.AddIntegrationAppLifeCycle();
s.AddSerilog();
}

public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

最佳答案

有一个开源库Corvus.Testing.AzureFunctions可用于在 Azure Functions 上执行集成测试。我在 xUnit 测试项目中复制了完整的库,并创建了 2 个类来启动和测试 Azure Function CreateObject。以下是这些类:

CreateObjectFixture.cs

该类主要设置测试日志位置和azure函数位置。它还启动并停止函数宿主环境。

public class CreateObjectFixture : IAsyncLifetime
{
private readonly FunctionsController function;

public CreateObjectFixture(IMessageSink output)
{
ILogger logger = new LoggerFactory()
.AddSerilog(
new LoggerConfiguration()
.WriteTo.File(@$"C:\temp\{this.GetType().FullName}.log")
.WriteTo.TestOutput(output)
.MinimumLevel.Debug()
.CreateLogger())
.CreateLogger("CreateObject Tests");

this.function = new FunctionsController(logger);
}

public int Port => 7071;

public async Task InitializeAsync()
{
await this.function.StartFunctionsInstance(
@"Get.Caa.AzureIntegrationsApp",
this.Port,
"net6.0");
}

public Task DisposeAsync()
{
this.function.TeardownFunctions();
return Task.CompletedTask;
}
}

CreateObjectTests.cs

此类使用fixture启动主机环境并向azure函数CreateObject发送POST请求。我也用过xUnitHelper用于轻松处理 JSON 文件的库。

[Trait("Category", "Integration")]
public class CreateObjectTests : IClassFixture<CreateObjectFixture>
{
private readonly CreateObjectFixture _fixture;
private readonly HttpClient _httpClient;

public CreateObjectTests(CreateObjectFixture fixture)
{
this._fixture = fixture;
this._httpClient = new HttpClient();
}

private int Port => _fixture.Port;

private string Uri => $"http://localhost:{this.Port}/CreateObject";

[Theory]
[JsonFileData(@".\Integration\CreateObjectTests\Data\Customer.json", typeof(JObject), typeof(JObject))]
public async Task ValidBody_ReturnCompleteNa(JObject data, JObject result)
{
// Arrange
var entityList = data["entityList"]!;
var input = new Dictionary<string, object> { { "Body", entityList.ToString() } };
var requestBody = new StringContent(
JObject.FromObject(input).ToString(Formatting.None),
Encoding.UTF8,
"application/json");
// Act
var output = await this._httpClient.PostAsync(Uri, requestBody).ConfigureAwait(false);

// Assert
Assert.NotNull(output);
}
}

关于c# - 如何在Azure Function上执行基于xUnit的集成测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73958847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com