![](/img/trans.png)
[英]How to mock MediatR to perform xUnit test for Web API Controller
[英]How to perform xUnit based Integration Test on Azure Function?
我不知道如何为 Azure Function 设置基于xUnit
的集成测试。我有 .NET 6.0-based Azure function CreateObject
。 我想对这个 function 进行一次集成测试。function 使用以下外部组件:
这是 Azure Function。
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;
}
}
这是 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
我不确定是否必须使用 Refit 来调用 Azure function?
using Refit;
namespace Get.Caa.IntegrationsApp.Test.Integration.Clients;
public interface ICreateObjectWorkflowClient
{
[Post("/api/CreateObject/")]
Task<object> Run(Dictionary<string, object> input);
}
我不确定是否必须使用 _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);
}
}
我不确定是否必须使用 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 进行集成测试?
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 函数执行集成测试。 我在我的 xUnit 测试项目中复制了完整的库,并创建了 2 个类来启动和测试 Azure Function CreateObject
。 以下是这些课程:
这个class基本设置了测试日志位置和azure function位置。 它还会启动 function 主机环境并将其停止。
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;
}
}
这个 class 使用 fixture 来启动主机环境并向 azure function 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.