WebApplicationFactory throws error that contentRootPath does not exist in ASP.NET Core integration test

后端 未结 6 1212
醉梦人生
醉梦人生 2021-02-13 18:52

I have a ASP.NET Core project with some simple Razor pages and a Web API controller.

I\'m using Clean Architecture as a starting point. I\'ve renamed the project names,

6条回答
  •  醉梦人生
    2021-02-13 19:47

    I'm not entirely sure what you're talking about, but you shouldn't be configuring stuff like this in a test project, in the first place. Instead, you should create a class like TestStartup and inherit from the SUT's Startup class. In the SUT's Startup class, you should factor out things like your DB setup and such into virtual private methods, which you can then override on TestStartup. For example, you could create a method like:

    private virtual void ConfigureDatabase(IServiceCollection services)
    {
        services.AddDbContext(o =>
            o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }
    

    Then in your TestStartup, you'd add something like:

    private override void ConfigureDatabase(IServiceCollection services)
    {
        var databaseName = Guid.NewGuid().ToString();
        services.AddDbContext(o =>
            o.UseInMemoryDatabase(databaseName));
    }
    

    Then, when setting up your factory for testing, you tell it to use your TestStartup:

    var client = factory.WithWebHostBuilder(b => b.UseStartup()).CreateClient();
    

    Or, you can create you own custom WebApplicationFactory and set it there:

    public class CustomWebApplicationFactory : WebApplicationFactory
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.UseStartup();
        }
    }
    

    Just bear in mind that the TStartup generic type param is for getting the entry point assembly, so you'd still put Startup there.

    The main point of this is that you don't need to repeat all your startup configuration, and then remember to keep in sync. Your test client will use the exact same startup config your actual apps uses, except for a few keep replacements like using an in-memory database.

提交回复
热议问题