我正在自定义WebApplicationFactory以使用Startup(来自原始Application项目的appsettings)。

目的是创建指向原始应用程序启动的集成测试。以下是dbcontext的appsettings json:

  "ConnectionStrings": {
    "DbConnection": "Data Source=.;Initial Catalog = TestDB; Integrated Security=True"

我想从下面的变量中覆盖服务以使用内存数据库。我将如何进行呢?

定制Web应用程序工厂:
namespace Integrationtest
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
            {
                var type = typeof(TStartup);
                var path = @"C:\OriginalApplication";

                configurationBuilder.AddJsonFile($"{path}\\appsettings.json", optional: true, reloadOnChange: true);
                configurationBuilder.AddEnvironmentVariables();
            });
        }
    }
}

实际集成测试:
public class DepartmentAppServiceTest : IClassFixture<CustomWebApplicationFactory<OriginalApplication.Startup>>

{
    public dbContextTest context;
    public CustomWebApplicationFactory<OriginalApplication.Startup> _factory;
    public DepartmentAppServiceTest(CustomWebApplicationFactory<OriginalApplication.Startup> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task DepartmentAppTest()
    {
        using (var scope = _factory.Server.Host.Services.CreateScope())
        {
            context.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName = "ABC" });
            context.SaveChanges();

            var foo = scope.ServiceProvider.GetRequiredService<IDepartmentAppService>();
            var departmentDto = await foo.GetDepartmentById(2);
            Assert.Equal("123", departmentDto.DepartmentCode);
        }
    }
}

我想从下面的此变量覆盖Services数据库以使用内存数据库。我将如何进行呢?
           var dbtest = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

           var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase(databaseName: "TestDB")
            .Options;

最佳答案

您可以使用 WebHostBuilder.ConfigureTestServices 调整集成测试服务器使用的服务配置。这样,您可以重新配置数据库上下文以使用其他配置。文档的integration testing chapter中也对此进行了介绍。

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    // …

    builder.ConfigureTestServices(services =>
    {
        // remove the existing context configuration
        var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<ApplicationDbContext>));
        if (descriptor != null)
            services.Remove(descriptor);

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseInMemoryDatabase("TestDB"));
    });
}

传递给ConfigureTestServices的配置将始终在Startup.ConfigureServices之后运行,因此您可以使用它来覆盖用于集成测试的实际服务。

在大多数情况下,只需在现有注册上注册其他类型就足以将其应用于所有地方。除非您实际上检索了单个类型的多个服务(通过在某处注入(inject)IEnumerable<T>),否则不会产生负面影响。

关于c# - 净核心: Override WebApplicationFactory Services DbContext with InMemory Database,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57385165/

10-13 06:58