如何单元测试DI中是否已注册Grpc拦截器?
如何测试gRPC拦截器是否已注册到依赖注入中
要验证ExceptionGrpcInterceptor是否已添加到gRPC的拦截器配置中,最直接的方式是检查GrpcServiceOptions里的拦截器集合,具体步骤如下:
- 构建测试用的服务集合,复现Startup中的gRPC配置逻辑
- 从服务集合创建服务提供器
- 获取
GrpcServiceOptions配置实例 - 检查拦截器列表中是否包含目标类型的注册项
示例测试代码(以xUnit为例)
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; public class GrpcInterceptorRegistrationTests { [Fact] public void ExceptionGrpcInterceptor_ShouldBeRegisteredInGrpcOptions() { // 1. 初始化服务集合并配置gRPC var services = new ServiceCollection(); services.AddGrpc(options => { options.Interceptors.Add<ExceptionGrpcInterceptor>(); }); // 2. 构建服务提供器 using var serviceProvider = services.BuildServiceProvider(); // 3. 获取gRPC服务配置选项 var grpcOptions = serviceProvider.GetRequiredService<IOptions<GrpcServiceOptions>>().Value; // 4. 验证拦截器是否存在 var interceptorExists = grpcOptions.Interceptors.Any(interceptor => interceptor.ServiceType == typeof(ExceptionGrpcInterceptor)); Assert.True(interceptorExists, "ExceptionGrpcInterceptor 未添加到gRPC拦截器配置中"); } }
补充说明
- 如果你的拦截器是通过实例或工厂委托添加的,需要调整检查逻辑:
- 实例添加:检查
interceptor.Instance.GetType()是否等于ExceptionGrpcInterceptor - 工厂委托:需要验证工厂最终会返回目标类型的实例(可结合DI解析测试)
- 实例添加:检查
- 仅检查DI中是否注册了
ExceptionGrpcInterceptor并不足够,因为注册了类型不代表它被添加到了gRPC的拦截器列表里,必须通过GrpcServiceOptions验证才能确保生效。
内容的提问来源于stack exchange,提问作者PassionateDeveloper
相关产品推荐
相关产品推荐

