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

jer*_*s38 6 c# .net-core asp.net-core

我正在自定义 WebApplicationFactory 以使用来自原始应用程序项目的启动、appsettings。

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

  "ConnectionStrings": {
    "DbConnection": "Data Source=.;Initial Catalog = TestDB; Integrated Security=True"
Run Code Online (Sandbox Code Playgroud)

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

自定义 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();
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实际集成测试:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

           var dbtest = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

           var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase(databaseName: "TestDB")
            .Options;
Run Code Online (Sandbox Code Playgroud)

pok*_*oke 10

您可以使用WebHostBuilder.ConfigureTestServices来调整集成测试服务器使用的服务配置。这样,您可以重新配置数据库上下文以使用不同的配置。这也包含在文档的集成测试章节中。

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"));
    });
}
Run Code Online (Sandbox Code Playgroud)

传递给该配置ConfigureTestServices将始终运行Startup.ConfigureServices,所以你可以用它来为你的集成测试覆盖了真正的服务。

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