如何在 ASP.NET 5/MVC 6 的单元测试中访问 HttpContext [英] How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6

查看:21
本文介绍了如何在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆