c# - 用于集成测试的 ASPNet.Core 托管环境?

标签 c# unit-testing asp.net-core asp.net-core-mvc-2.0

在为我的 ASPNet.Core 网络应用构建集成测试时,https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing , 我遇到了一个问题。 Startup 在我运行应用程序时运行,配置被读取并包含我的 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);
    }
}

我收到异常Missing configuration section ServiceConfig.

WebHost 在我的应用程序的 Program.cs 中是这样构建的:

WebHost.CreateDefaultBuilder(args)
       .UseStartup<Startup>()
       .UseKestrel(o => o.AddServerHeader = false)
       .Build();

问题可能在于它在测试代码中的构建方式不同吗?

修改后的 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();
}

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

public Startup(IConfiguration configuration, IHostingEnvironment environment)
        : base(typeof(Startup), configuration, environment)
{
}

根据@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>());

开始工作了,有点...

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();

但现在,HostingEnvironment 被设置为测试应用程序的目录与 Web 应用程序的目录,它尝试在 HomeController 构造函数中从那里读取 appsettings.json 文件,在这里:

public HSMController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
    contentRootPath = _hostingEnvironment.ContentRootPath;
}

最佳答案

ASP .Net Core 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);
        });
  }

然后在你的测试中

public SettingsTests()
{
  TestServer = new ApiTestServer();
  HttpClient = TestServer.CreateClient();
}

关于c# - 用于集成测试的 ASPNet.Core 托管环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46978553/

相关文章:

c# - Asp.net 核心 - 调用方法()不调用中间件

c# - 如何扩展 asp.net User.Identity 属性?

Angular Testing karma - 错误 : Can't resolve all parameters for RequestOptions: (?)

c# - 当从不同的目录运行时,记录器在 asp.net 应用程序中为 null

c# - 在 ASP.NET Core 中将 Razor View 渲染为字符串

c# - 在 ASP.Net Core 中验证 IFormFile 的图像类型

c# - System.Array 不包含 'Any' 的定义 - C#

c# - 将标签移出饼图

java - Spring Boot 在测试时模拟其他休息客户端

python - sys.stdin 的模型?