如何在 ASP.NET 5/MVC 6 的单元测试中访问 HttpContext

How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6(如何在 ASP.NET 5/MVC 6 的单元测试中访问 HttpContext)
本文介绍了如何在 ASP.NET 5/MVC 6 的单元测试中访问 HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在中间件的 http 上下文中设置了一个值.例如 HttpContext.User.

Lets say I am setting a value on the http context in my middleware. For example HttpContext.User.

如何在我的单元测试中测试 http 上下文.这是我正在尝试做的一个例子

How can test the http context in my unit test. Here is an example of what I am trying to do

中间件

public class MyAuthMiddleware
{
    private readonly RequestDelegate _next;

    public MyAuthMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.User = SetUser(); 
        await next(context);
    }
}

测试

[Fact]
public async Task UserShouldBeAuthenticated()
{
    var server = TestServer.Create((app) => 
    {
        app.UseMiddleware<MyAuthMiddleware>();
    });

    using(server)
    {
        var response = await server.CreateClient().GetAsync("/");
        // After calling the middleware I want to assert that 
        // the user in the HttpContext was set correctly
        // but how can I access the HttpContext here?
    }
}

推荐答案

以下是您可以使用的两种方法:

Following are two approaches you could use:

// Directly test the middleware itself without setting up the pipeline
[Fact]
public async Task Approach1()
{
    // Arrange
    var httpContext = new DefaultHttpContext();
    var authMiddleware = new MyAuthMiddleware(next: (innerHttpContext) => Task.FromResult(0));

    // Act
    await authMiddleware.Invoke(httpContext);

    // Assert
    // Note that the User property on DefaultHttpContext is never null and so do
    // specific checks for the contents of the principal (ex: claims)
    Assert.NotNull(httpContext.User);
    var claims = httpContext.User.Claims;
    //todo: verify the claims
}

[Fact]
public async Task Approach2()
{
    // Arrange
    var server = TestServer.Create((app) =>
    {
        app.UseMiddleware<MyAuthMiddleware>();

        app.Run(async (httpContext) =>
        {
            if(httpContext.User != null)
            {
                await httpContext.Response.WriteAsync("Claims: "
                    + string.Join(
                        ",",
                        httpContext.User.Claims.Select(claim => string.Format("{0}:{1}", claim.Type, claim.Value))));
            }
        });
    });

    using (server)
    {
        // Act
        var response = await server.CreateClient().GetAsync("/");

        // Assert
        var actual = await response.Content.ReadAsStringAsync();
        Assert.Equal("Claims: ClaimType1:ClaimType1-value", actual);
    }
}

这篇关于如何在 ASP.NET 5/MVC 6 的单元测试中访问 HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)