【问题标题】:WebApplicationFactory use ConfigureServices or ConfiguresTestServicesWebApplicationFactory 使用 ConfigureServices 或 ConfiguresTestServices
【发布时间】:2022-08-24 04:41:30
【问题描述】:

我想测试 ASP.NET Core 6 应用程序。我创建了一个继承自WebApplicationFactory 的自定义工厂,在ConfigureWebHost 方法中,我必须使用builder.ConfigureServicesbuilder.ConfigureTestService 吗?

我不明白其中的区别。

例如:

        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder
                .ConfigureTestServices(services => //Or ConfigureServices ?
                {
                    var descriptor = services.SingleOrDefault(
                        d => d.ServiceType ==
                            typeof(DbContextOptions<OnDemandContext>));

                    if (descriptor != null)
                    {
                        services.Remove(descriptor);
                    }
                    
                    services.AddDbContextPool<OnDemandContext>(options =>
                    {
                        options.UseInMemoryDatabase(\"fakeDatabase\");
                    });
                });
        }

    标签: c# asp.net-core integration-testing


    【解决方案1】:

    您不必致电builder.ConfigureTestServices,但它允许您重新配置、覆盖或用其他东西替换以前注册的服务。它在您的 ConfigureServices 方法被调用后执行。

    在下面的示例中,testcontainers 用于替换普通的数据库连接字符串提供程序,WebMotions.Fake.Authentication.JwtBearer 用于创建假 Jwt 不记名令牌以进行集成测试

        builder.ConfigureTestServices(services =>
        {
            services.AddAuthentication(FakeJwtBearerDefaults.AuthenticationScheme).AddFakeJwtBearer();
            services.RemoveAll(typeof(IHostedService));
            services.RemoveAll(typeof(IConnectionStringProvider));
            var containerString = new ConnectionStringOptions
            {
                Application = "testContainer",
                Primary = Container.ConnectionString
            };
            services.AddSingleton<IConnectionStringProvider>(_ =>
                new ConnectionStringProvider(containerString));
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2021-05-11
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      相关资源
      最近更新 更多