Net Core: Execute All Dependency Injection in Xunit Test for AppService, Repository, etc

后端 未结 3 1518
暖寄归人
暖寄归人 2020-11-28 11:37

I am trying to implement Dependency Injection in Xunit test for AppService. Ideal goal is to run the original application program Startup/configuration, and use any depende

3条回答
  •  悲&欢浪女
    2020-11-28 11:50

    Use Custom Web Application Factory and ServiceProvider.GetRequiredService below, feel free to edit and optimize the answer

    CustomWebApplicationFactory:

    public class CustomWebApplicationFactory : WebApplicationFactory 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();
            });
    
            // if you want to override Physical database with in-memory database
            builder.ConfigureServices(services =>
            {
                var serviceProvider = new ServiceCollection()
                    .AddEntityFrameworkInMemoryDatabase()
                    .BuildServiceProvider();
    
                services.AddDbContext(options =>
                {
                    options.UseInMemoryDatabase("DBInMemoryTest");
                    options.UseInternalServiceProvider(serviceProvider);
                });
            });
        }
    }
    

    Integration Test:

    public class DepartmentAppServiceTest : IClassFixture>
    {
        public CustomWebApplicationFactory _factory;
        public DepartmentAppServiceTest(CustomWebApplicationFactory factory)
        {
            _factory = factory;
            _factory.CreateClient();
        }
    
        [Fact]
        public async Task ValidateDepartmentAppService()
        {      
            using (var scope = _factory.Server.Host.Services.CreateScope())
            {
                var departmentAppService = scope.ServiceProvider.GetRequiredService();
                var dbtest = scope.ServiceProvider.GetRequiredService();
                dbtest.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName = "ABC" });
                dbtest.SaveChanges();
                var departmentDto = await departmentAppService.GetDepartmentById(2);
                Assert.Equal("123", departmentDto.DepartmentCode);
            }
        }
    }
    

    Resources:

    https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2

    https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api

提交回复
热议问题