You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求.NET 6 Azure函数应用中IFunctionsWorkerMiddleware单元测试示例

针对IFunctionsWorkerMiddleware的.NET 6函数应用单元测试配置示例

问题背景

需要为Microsoft.Azure.Functions.Worker.Middleware.IFunctionsWorkerMiddleware编写单元测试,但现有示例均针对MVC场景,尝试配置时还会遇到函数应用默认启动gRPC服务的问题。

核心解决思路

测试Worker中间件无需依赖真实gRPC服务或测试服务器,通过模拟FunctionContext+依赖注入构建中间件管道即可完成测试,同时可通过配置禁用不必要的gRPC端点。

测试示例实现

1. 测试项目依赖

确保安装以下NuGet包:

  • Microsoft.Azure.Functions.Worker
  • Microsoft.Azure.Functions.Worker.Testing
  • 测试框架(如xunit/nunit)
  • 模拟工具(如Moq)

2. 完整测试代码

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Moq;
using Xunit;

public class MyMiddlewareTests
{
    [Fact]
    public async Task MyMiddleware_Executes_As_Expected()
    {
        // 构建测试主机,配置Functions Worker服务
        var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults(builder =>
            {
                // 将自定义中间件添加到执行管道
                builder.UseMiddleware<MyMiddleware>();
                // 注册模拟依赖
                builder.Services.AddSingleton(Mock.Of<IMyMiddlewareDependency>());
            })
            // 禁用gRPC端点,避免测试时启动额外服务
            .ConfigureServices(services =>
            {
                services.Configure<WorkerOptions>(options =>
                {
                    options.GrpcEndpoint = null;
                });
            })
            .Build();

        await host.StartAsync();

        try
        {
            // 获取中间件管道实例
            var pipeline = host.Services.GetRequiredService<IMiddlewarePipeline>();
            
            // 模拟FunctionContext,按需设置必要属性
            var mockContext = new Mock<FunctionContext>();
            mockContext.Setup(c => c.InvocationId).Returns(Guid.NewGuid());

            // 执行中间件管道,传入模拟的后续执行逻辑
            await pipeline.InvokeAsync(mockContext.Object, context => Task.CompletedTask);

            // 验证中间件行为,比如检查依赖方法是否被调用
            var dependency = host.Services.GetRequiredService<IMyMiddlewareDependency>();
            Mock.Get(dependency).Verify(d => d.ProcessRequest(), Times.Once);
        }
        finally
        {
            await host.StopAsync();
            host.Dispose();
        }
    }
}

// 示例自定义中间件
public class MyMiddleware : IFunctionsWorkerMiddleware
{
    private readonly IMyMiddlewareDependency _dependency;

    public MyMiddleware(IMyMiddlewareDependency dependency)
    {
        _dependency = dependency;
    }

    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        // 中间件前置处理逻辑
        _dependency.ProcessRequest();
        
        // 执行后续管道/函数逻辑
        await next(context);
        
        // 中间件后置处理逻辑
    }
}

// 示例中间件依赖接口
public interface IMyMiddlewareDependency
{
    void ProcessRequest();
}

关键说明

  • 使用ConfigureFunctionsWorkerDefaults是配置函数应用服务和中间件的标准方式,确保测试环境与生产环境一致。
  • 设置WorkerOptions.GrpcEndpoint = null可直接禁用gRPC服务启动,解决测试时的gRPC相关报错。
  • 通过IMiddlewarePipeline手动触发中间件执行,配合模拟的FunctionContext,无需启动完整函数服务即可验证中间件逻辑。

内容的提问来源于stack exchange,提问作者Chris Fink

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:46:02