asp.net core web Api integration testing with startup having static file configuration

446 Views Asked by At

I was trying to implement integration testing for my api. But, it is saying System.IO.DirectoryNotFoundException : ..WebApi.IntegrationTest\bin\Debug\net6.0\Files\ while I run the test

here is my startup code

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
     
            }
            app.UseBlazorFrameworkFiles();
            
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Files")),
                RequestPath = new PathString("/Files")
            });
            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors("CorsPolicy");
             app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.Initialize(Configuration);
        }

when I comment out UseStaticFiles it passes the test else it fails with the above. exception

here is my CustomWebApplicationFactory

 public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseInMemoryDatabase("ApplicationDbContextInMemoryTest");
            })
            .AddControllers()
            .AddApplicationPart(typeof(Startup).Assembly);

            var sp = services.BuildServiceProvider();
            using (var scope = sp.CreateScope())
            {
                var scopedService = scope.ServiceProvider;
                var context = scopedService.GetRequiredService<ApplicationDbContext>();
                var logger = scopedService.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();

                context.Database.EnsureCreated();
                try
                {
                    Utilities.InitializeDbForTests(context);
                }
                catch (Exception ex)
                {

                    logger.LogError(ex, $"An error occured seeding the database with test messages, Error: {ex.Message}");
                }
            }
        });
    }
    protected override IHost CreateHost(IHostBuilder builder)
    {
        builder.UseContentRoot(Directory.GetCurrentDirectory());
        return base.CreateHost(builder);
    }
    public HttpClient GetAnonymousClient()
    {
        return CreateClient();
    }
}

I tried a lot to fix it but I was not able, please help me, thank you!

0

There are 0 best solutions below