亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 InMemory 數據庫覆蓋 WebApplicationFactory

使用 InMemory 數據庫覆蓋 WebApplicationFactory

C#
臨摹微笑 2023-08-13 16:26:11
我正在自定義 WebApplicationFactory 以使用原始應用程序項目中的 Startup、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);        }    }}
查看完整描述

1 回答

?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

您可以用來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"));

? ? });

}

傳遞給的配置ConfigureTestServices將始終在 后運行,因此Startup.ConfigureServices您可以使用它來覆蓋集成測試的實際服務。


對于大多數情況,只需在現有注冊上注冊其他類型即可使其適用于所有地方。除非您實際上檢索單一類型的多個服務(通過注入IEnumerable<T>某處),否則這不會產生負面影響。


查看完整回答
反對 回復 2023-08-13
  • 1 回答
  • 0 關注
  • 169 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號