如何单元测试拦截器是否在依赖注入中注册?

huangapple go评论55阅读模式
英文:

How to unit test if an interceptor is registered within the DI?

问题

如何测试我的应用程序是否已在DI中注册了这个拦截器?

英文:

I have my startup like this:

builder.Services.AddGrpc(options =>
    {
        options.Interceptors.Add<ExceptionGrpcInterceptor>(); // << how to test if this is there
    });

Now I want to test if my application has this interceptor registered within the DI.

How to do that?

答案1

得分: 1

从 DI 容器获取选项对象

使用 ConsoleApp1;
使用 Grpc.AspNetCore.Server;
使用 Microsoft.Extensions.DependencyInjection;
使用 Microsoft.Extensions.Options;

IServiceCollection 服务集合 = new ServiceCollection();
services.AddGrpc(options =>
{
options.Interceptors.Add();
});

IServiceProvider 服务提供程序 = services.BuildServiceProvider();

var options = 服务提供程序.GetRequiredService<IOptions>();

bool hasInterceptor = options.Value.Interceptors.Any(x => x.Type == typeof(ExceptionGrpcInterceptor));

Console.ReadKey();

英文:

You can get options object from DI container

using ConsoleApp1;
using Grpc.AspNetCore.Server;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

IServiceCollection services = new ServiceCollection();
services.AddGrpc(options =&gt;
{
    options.Interceptors.Add&lt;ExceptionGrpcInterceptor&gt;();
});

IServiceProvider serviceProvider = services.BuildServiceProvider();

var options = serviceProvider.GetRequiredService&lt;IOptions&lt;GrpcServiceOptions&gt;&gt;();

bool hasInterceptor = options.Value.Interceptors.Any(x =&gt; x.Type == typeof(ExceptionGrpcInterceptor));

Console.ReadKey();

huangapple
  • 本文由 发表于 2023年4月19日 15:27:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76051794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定