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

查看:135
本文介绍了如何访问HttpContext的单元测试里面ASP.NET 5/6 MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我设置在我中间件HTTP上下文的值。例如HttpContext.User中。

如何测试在我的单元测试的HTTP上下文。这里是什么我试图做一个例子

中间件

 公共类MyAuthMiddleware
{
    私人只读RequestDelegate _next;    公共MyAuthMiddleware(RequestDelegate旁边)
    {
        _next =下一个;
    }    公共异步任务调用(HttpContext的背景下)
    {
        context.User = SETUSER();
        接下来的等待(背景);
    }
}

测试

  [事实]
公共异步任务UserShouldBeAuthenticated()
{
    VAR服务器= TestServer.Create((APP)=>
    {
        app.UseMiddleware< MyAuthMiddleware>();
    });    使用(服务器)
    {
        VAR响应=等待server.CreateClient()GetAsync(/)。
        //调用中间件后,我想断言
        //在HttpContext的用户设置正确
        //但我怎么能在这里访问的HttpContext?
    }
}


解决方案

以下是两种方法可以使用​​:

  //直接测试中间件本身不设置管道
[事实]
公共异步任务Approach1()
{
    //安排
    VAR的HttpContext =新DefaultHttpContext();
    VAR authMiddleware =新MyAuthMiddleware(NEXT:(innerHttpContext)=> Task.FromResult(0));    //法案
    等待authMiddleware.Invoke(HttpContext的);    //断言
    //请注意,DefaultHttpContext用户属性是永远不能为null等做
    为主要内容//专项检查(例如:索赔)
    Assert.NotNull(HttpContext.User中);
    VAR声称= httpContext.User.Claims;
    // TODO:核实这些索赔
}[事实]
公共异步任务Approach2()
{
    //安排
    VAR服务器= TestServer.Create((APP)=>
    {
        app.UseMiddleware< MyAuthMiddleware>();        app.Run(异步(HttpContext的)=>
        {
            如果(HttpContext.User中!= NULL)
            {
                等待httpContext.Response.WriteAsync(索赔
                    +的string.join(
                        ,,
                        httpContext.User.Claims.Select(权利= GT;的String.Format({0}:{1},claim.Type,claim.Value))));
            }
        });
    });    使用(服务器)
    {
        //法案
        VAR响应=等待server.CreateClient()GetAsync(/)。        //断言
        VAR实际=等待response.Content.ReadAsStringAsync();
        Assert.Equal(声明:ClaimType1:ClaimType1价值,实际);
    }
}

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

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

Middleware

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);
    }
}

Test

[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);
    }
}

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

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