c# - 如何对使用 Response.OnStarting 的 .NET 中间件进行单元测试

标签 c# asp.net-core testing middleware xunit

因此,我创建了一个 .net 核心中间件,它为响应添加了 header 。
我没有找到对这个中间件进行单元测试的方法,因为它使用 OnStarting回调,我无法想象如何模拟或强制执行它。

这是中间件的示例:

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
    context.Response.OnStarting(() =>
    {
        context.Response.Headers.Add("Name", "Value");

        return Task.CompletedTask;
    });

    await next(context);
}

由于中间件接口(interface)需要 HttpContext 的具体实例,我无法想象使用 FakeItEasy 模拟它的方法, 例如。

最佳答案

您可以使用 Mock HttpContext for unit testing a .NET core MVC controller? 中的示例作为指南:

using Shouldly;
using Xunit;

[Fact]
public async Task Middleware_should_add_header()
{
    // Arrange:

    HttpContext ctx = new DefaultHttpContext();

    RequestDelegate next = ( HttpContext hc ) => Task.CompletedTask;

    MyMiddleware mw = new MyMiddleware();

    // Act - Part 1: InvokeAsync set-up:

    await hw.InvokeAsync( ctx, next );

    // Assert - Part 1

    ctx.Response.Headers.TryGetValue( "Name", out String value0 ).ShouldBeFalse();
    value0.ShouldBeNull();

    // Act - Part 2

    await ctx.Response.StartAsync( default );

    // Asset - Part 2

    ctx.Response.Headers.TryGetValue( "Name", out String value1 ).ShouldBeTrue();
    value1.ShouldBe( "Value" );

}

关于c# - 如何对使用 Response.OnStarting 的 .NET 中间件进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59583406/

相关文章:

c# - 在 Entity Framework Core 上禁用 AutoDetectChanges

c# - 修改后的请求路径上的 HttpContext GetEndpoint .net 5

testing - 使用 Gradle 多次运行单个测试

debugging - 使用内存数据源进行验收测试不起作用

C#:在不相关的类之间共享属性、事件和方法

C# 接口(interface)方法不保存在 .dll 中,不是接口(interface)的成员

c# - LINQ 查询 if 条件外部参数

testing - 自定义 Rally Grid 列和 Rally 数据列

c# - XML 序列化错误 - 类型 'ItemsElementName' 的选择标识符 'ItemsChoiceType[]' 的值无效或缺失

c# - 我如何将我的类的属性发送到函数中