【问题标题】:How to mock a web api for testing如何模拟 web api 进行测试
【发布时间】:2020-03-11 14:35:54
【问题描述】:

我有一个类库,其中包含一些DelegationHandlers,很简单,获取请求,根据请求内容添加一些标头并传递请求。

所以我需要为我的库编写单元测试。我正在使用 .NET Core 2.1 和 xunit,我想知道是否有办法模拟 Web 服务器,然后我可以使用我的库向该 Web 服务器发送请求并检查我的请求结果?知道如何模拟 Web 服务器(应用程序)吗?或者我如何通过发送 http 请求来测试我的库?

【问题讨论】:

  • 您是否尝试过为此使用TestServer?这个article 可能会有所帮助
  • @PavelAnikhouski 据我所知,在 TestServer 中您已经有一个 Web 应用程序或 api,然后您将使用 TestServer 启动该应用程序进行测试。在我的情况下,我只有一个类库,我怎么能启动一个 TestServer 不存在的 web api?
  • @Saeid 我认为这个想法是您制作一个 Test.WebApp 项目,然后您可以使用 WebApplicationFactory 并将其链接到该 Startup 类,以便拥有一个存在的 WebApi。我很感激这并不理想
  • @JonE 感谢您的评论,我考虑过这一点,但我想知道为什么没有人考虑这种情况,要么我错过了一些东西,要么可能已经有了解决方案。

标签: unit-testing .net-core integration-testing xunit


【解决方案1】:

我在这里找到了一个解决方案,我分享它可能对其他人有用。

public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, RequestDelegate del)
{
    _builder = new WebHostBuilder()
        .UseUrls(baseUrl)
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .Configure(app =>
        {
            app.UsePathBase(basePath);
            app.Run(del);
        })
        .Build();

    _builder.Start();
}

我们在集成测试中使用的 WebHostBuilder,现在我们可以通过 RequestDelegate 来运行应用程序:

GivenThereIsAServiceRunningOn(baseUrl, basePath, async context =>
{
    _downstreamPath = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value;

    if (_downstreamPath != basePath)
    {
        context.Response.StatusCode = statusCode;
        await context.Response.WriteAsync("downstream path didn't match base path");
    }
    else
    {
        context.Response.StatusCode = statusCode;
        await context.Response.WriteAsync(responseBody);
    }
});

【讨论】:

    【解决方案2】:

    如果您正在编写单元测试,则不需要启动测试服务器。但是,要使用模拟控制器进行集成测试,可以使用 microsoft 的测试服务器

    https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1

    【讨论】:

    • 这不是答案,提供链接根本无济于事
    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 2020-03-31
    • 2021-08-26
    • 1970-01-01
    • 2021-09-19
    • 2020-04-06
    • 1970-01-01
    • 2010-11-01
    相关资源
    最近更新 更多