关于c#:Asp Net Core WebHostBuilder集成测试期间的奇怪行为

Asp Net Core WebHostBuilder strange behavior during integration testing

我在使用Asp Net Core制作的Web应用程序上工作,我尝试使用TestServer进行集成测试。

我按照此博客文章设置了我的
测试环境。

该应用程序的Startup.cs如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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?}");
        });
    }
}

对于集成测试,我使用以下代码创建WebHostBuilder

1
2
3
4
5
6
7
8
  var builder = new WebHostBuilder()
  .UseContentRoot(appRootPath)
  .UseStartup<TStartup>()
  .UseEnvironment("test")
  .ConfigureServices(x =>
  {
      .AddWebEncoders();
  });

如果我运行一个简单的测试,它将检查是否可以访问主页,则它可以工作。

对于某些理由,我必须在"启动"中更改一些配置。 所以我在WebHostBuilder的Configure上添加了一个调用:

1
2
3
4
5
6
7
8
9
10
11
var builder = new WebHostBuilder()
.UseContentRoot(appRootPath)
.UseStartup<TStartup>()
.UseEnvironment("test")
.ConfigureServices(x =>
{
    .AddWebEncoders();
})
.Configure(x => {
// Some specific configuration
});

而且,我不知道为什么(这就是为什么我需要您的帮助),当我像以前一样调试相同的简单测试时,
永远不会调用启动类的ConfigureServices和Configure方法...
即使只是让Configure方法为空。

这是正常行为吗?

如何设置特定的配置而不将其直接添加到Startup.cs中?


WebHostBuilder.Configure代替UseStartup,它们不能一起使用。 相反,您可以在ConfigureServices中注册一个IStartupFilter。 看这里。