Net Core:使用InMemory数据库覆盖WebApplicationFactory服务DbContext

时间:2019-08-06 23:24:05

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

我正在自定义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;

1 个答案:

答案 0 :(得分:3)

您可以使用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之后运行 ,因此您可以使用它来覆盖用于集成测试的实际服务。

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