用于集成测试的ASPNet.Core HostingEnvironment?

MB3*_*B34 5 c# unit-testing asp.net-core asp.net-core-mvc-2.0

在为我的ASPNet.Core Web应用程序(https://docs.microsoft.com/zh-cn/aspnet/core/testing/integration-testing)构建集成测试时,遇到了一个问题。当我运行应用程序并读取配置并包含apsettings.json文件中的所有信息时,将运行启动程序。现在,当我运行集成测试时,如下所示。启动已运行,但配置不同。为什么会发生这种情况?我如何确保它读取应用程序本身的内容?

[TestFixture]
class HSMControllerTests
{
    private readonly TestServer _server;
    private readonly HttpClient _client;

    public HSMControllerTests()
    {
        _server = new TestServer(new WebHostBuilder()
        .UseStartup<Startup>());
        _client = _server.CreateClient();
    }

    [Test]
    public async global::System.Threading.Tasks.Task GET_PingHSM_ShouldSucceedAsync()
    {
        HttpResponseMessage response = await _client.GetAsync("HSM/PingHSM");
        Assert.NotNull(response);
        Assert.IsInstanceOf<OkObjectResult>(response);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在例外 Missing configuration section ServiceConfig.

这是Program.cs在我的应用程序中内置WebHost的方式:

WebHost.CreateDefaultBuilder(args)
       .UseStartup<Startup>()
       .UseKestrel(o => o.AddServerHeader = false)
       .Build();
Run Code Online (Sandbox Code Playgroud)

在测试代​​码中如何构建它的差异可能是问题吗?

修改后的ControllerTest构造函数:

public HSMControllerTests()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Path.GetFullPath(@"../../../../HSM.WebApi.IntegrationTests"))
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();

    _server = new TestServer(WebHost.CreateDefaultBuilder()
        .UseStartup<Startup>());
    _client = _server.CreateClient();
}
Run Code Online (Sandbox Code Playgroud)

现在,如何将新的配置注入启动中?我们的启动定义如下:

public Startup(IConfiguration configuration, IHostingEnvironment environment)
        : base(typeof(Startup), configuration, environment)
{
}
Run Code Online (Sandbox Code Playgroud)

根据@poke的最新帖子进行修改

_server = new TestServer(WebHost.CreateDefaultBuilder()
    .ConfigureAppConfiguration(configBuilder => new ConfigurationBuilder()
        .SetBasePath(Path.GetFullPath(@"../../../../HSM.WebApi.IntegrationTests"))
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables()
    )
    .UseStartup<Startup>());
Run Code Online (Sandbox Code Playgroud)

正常工作了...

var config = new ConfigurationBuilder()
    .SetBasePath(Path.GetFullPath(@"../../../../HSM.WebApi.IntegrationTests"))
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables();

var Configuration = config.Build();

_server = new TestServer(WebHost.CreateDefaultBuilder()
    .UseConfiguration(Configuration)
    .UseStartup<Startup>());
_client = _server.CreateClient();
Run Code Online (Sandbox Code Playgroud)

但是现在,HostingEnvironment设置为Tests应用程序的目录,而不是Web应用程序的目录,并且它尝试appsettings.json从此处读取HomeController构造函数中的文件:

public HSMController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
    contentRootPath = _hostingEnvironment.ContentRootPath;
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*mer 7

ASP .Net 核心 2.0

将 appsettings.json 文件复制到集成测试并将它们设置为始终复制。

创建 MyTestServer 类,因为它可能会在许多测试中重复使用。请记住, CreateDefaultBuilder 将自动加载您的应用设置和使用环境。

  public class ApiTestServer : TestServer
  {
    public ApiTestServer() : base(WebHostBuilder())
    { }

    private static IWebHostBuilder WebHostBuilder() =>
      WebHost.CreateDefaultBuilder()
        .UseStartup<Startup>()
        .UseEnvironment("Local")
        .UseKestrel(options =>
        {
          options.Listen(IPAddress.Any, 5001);
        });
  }
Run Code Online (Sandbox Code Playgroud)

然后在你的测试中

public SettingsTests()
{
  TestServer = new ApiTestServer();
  HttpClient = TestServer.CreateClient();
}
Run Code Online (Sandbox Code Playgroud)


MB3*_*B34 5

appsettings.json文件复制到集成测试项目文件夹,并将其设置为“始终复制”,即可正常工作。