Is it possible to use Dependency Injection with xUnit?

前端 未结 4 1218
忘掉有多难
忘掉有多难 2021-02-06 22:25

I have a test class with a constructor that needs an IService.

public class ConsumerTests
{
    private readonly IService          


        
4条回答
  •  别跟我提以往
    2021-02-06 23:02

    Yes there is now, these two questions and answers should be consolidated in my opinion, see answer here

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

    Use Custom Web Application Factory and ServiceProvider.GetRequiredService below, feel free to edit and optimize 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

提交回复
热议问题