C# xUnit测试Azure函数w/.NET 5

C# xUnit测试Azure函数w/.NET 5,c#,.net-core,azure-functions,asp.net-core-5.0,C#,.net Core,Azure Functions,Asp.net Core 5.0,我正试图找到一种方法来为我的Azure函数设计xUnit测试,这是基于示例的 如您所见,使用.net 5函数,您需要在函数的项目目录中启动func host start,然后可以启动函数并进行调试 这是函数项目的program.cs var host = new HostBuilder() .ConfigureAppConfiguration(c => { c.AddComman

我正试图找到一种方法来为我的Azure函数设计xUnit测试,这是基于示例的

如您所见,使用.net 5函数,您需要在函数的项目目录中启动
func host start
,然后可以启动函数并进行调试

这是函数项目的program.cs

var host = new HostBuilder()
           .ConfigureAppConfiguration(c =>
           {                   
               c.AddCommandLine(args);
           })
           .ConfigureFunctionsWorker((c, b) =>
           {
               b.UseMiddleware<FunctionExceptionMiddleware>(); //an extension method of mine to register middlewares...
               b.UseFunctionExecutionMiddleware();
           })
           .ConfigureServices(s =>
           {
               //add other services here,
               
               CloudStorageAccount storageAccount = CloudStorageAccount.Parse("");
               BlobServiceClient blobServiceClient = new BlobServiceClient("");

               s.AddScoped(r => storageAccount);
               s.AddScoped(r => blobServiceClient);

           })
           .Build();
据我所知,为了获得最佳测试,需要从工具箱中启动
func.exe
,然后使用
HttpClient
我可以向
http://localhost:7071/api/MyFunction

我曾想过在每次测试之前通过
Process.Start()
启动
func.exe
,但这有点像黑客,因为我真的不知道它什么时候准备好了(func.exe在显示“Worker Process started and initialized”消息之前编译所有程序集),测试可能会因此失败


有什么想法吗?

我不想用这种方式测试函数,也不想依赖主机。如果正确设计了函数,您可以将它们作为普通类单独测试(或者,让它们传递给您可以测试的对象),并模拟依赖关系,或者使用ServiceCollection/Provider解析函数对象。因此,不要使用CloudStorageAccount,它是旧的。BlobService客户端可能过于依赖于您引用的库。较新的azure storage SDK实际上有内置的方法用于在DI中注册队列/blob客户端。我强烈建议使用它,它可以与net5函数一起工作well@pinkfloydx33
HttpRequestData
似乎不是真正可以模仿的。我有从其
Url
属性检索查询字符串参数的逻辑,它是只读的-无法从xunit测试中设置它。我有一些azure函数,其中包括测试httprequest,但这是针对3.x的。。。如果我有时间,我会看看是否能找到他们和他们的测试。如果我记得的话,这必须以迂回的方式进行,但这是可能的
[FunctionName("GetAsset")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req, FunctionExecutionContext executionContext)
{
    var response = new HttpResponseData(HttpStatusCode.OK);

    
    var container = req.GetQueryStringParam("container"); //extension method to retrieve query parameters...
    var blob = req.GetQueryStringParam("blob");


    if (string.IsNullOrEmpty(container) || string.IsNullOrEmpty(blob))
    {
        executionContext.Logger.LogInformation($"GetAsset function - missing arguments in request string");
        return new BadRequestObjectResult("");
    }


    return new OkObjectResult("Success");
}