【问题标题】:Asp Net Core WebHostBuilder strange behavior during integration testing集成测试期间的 Asp Net Core WebHostBuilder 奇怪行为
【发布时间】:2017-03-03 11:42:38
【问题描述】:

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

我按照blog post 设置了我的 测试环境。

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

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

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

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

出于某些原因,我必须更改启动中的一些配置。所以我在 Configure on WebHostBuilder 添加了一个调用:

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

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

这种行为正常吗?

如何在不直接添加到 Startup.cs 的情况下设置特定配置?

【问题讨论】:

    标签: c# asp.net asp.net-core integration-testing


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 2013-03-23
    • 2016-05-15
    • 2019-12-14
    • 2020-07-05
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多