如何模拟 web api 进行测试

How to mock a web api for testing

我有一个class库,其中包含一些DelegationHandlers,很简单,获取请求,根据请求内容添加一些headers,然后将请求传递下去。

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

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

的测试服务器

https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.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);
    }
});