Waldo
Waldo

Reputation: 1155

Asp Net Core WebHostBuilder strange behavior during integration testing

I work on an Web Application made with Asp Net Core and I try to use TestServer for integration testing.

I followed this blog post to setup my test enviroment.

The Startup.cs of the application look like this :

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        applicationPath = env.WebRootPath;
        contentRootPath = env.ContentRootPath;
        // Setup configuration sources.

        var builder = new ConfigurationBuilder()
            .SetBasePath(contentRootPath)
            .AddJsonFile("appsettings.json")
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Many services are called here
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
    {
      // Many config are made here
        loggerFactory.AddSerilog();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=auth}/{action=login}/{id?}");
        });
    }
}

For the integration test I use this code for create WebHostBuilder

  var builder = new WebHostBuilder()
  .UseContentRoot(appRootPath)
  .UseStartup<TStartup>()
  .UseEnvironment("test")
  .ConfigureServices(x =>
  {
      .AddWebEncoders();
  });

If I run a simple test that will check if home page is accessible it works.

For some raison I have to change some configuration in the Startup. So I add a call at Configure on WebHostBuilder :

var builder = new WebHostBuilder()
.UseContentRoot(appRootPath)
.UseStartup<TStartup>()
.UseEnvironment("test")
.ConfigureServices(x =>
{
    .AddWebEncoders();
})
.Configure(x => {
// Some specific configuration
});

And, I don't know why (that's why I need your help), when I debug the same simple test like before, the ConfigureServices and Configure method of the startup class are never called... Even when I just let the Configure method blank.

Is this behavoir normal?

How can I set up specific configuration without adding it directly in the Startup.cs ?

Upvotes: 0

Views: 940

Answers (1)

Tratcher
Tratcher

Reputation: 6074

WebHostBuilder.Configure replaces UseStartup, they can't be used together. Instead you can register an IStartupFilter inside ConfigureServices. Look here.

Upvotes: 1

Related Questions