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

Sul*_*Aga 11 asp.net unit-testing httpcontext asp.net-core-mvc

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

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

中间件

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

测试

[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?
    }
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*lla 13

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

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Tuu*_*oos 7

asp.net 5/MVC6的RC1版本可以在单元测试中手动设置HttpContext,这太棒了!

        DemoController demoController = new DemoController();
        demoController.ActionContext = new ActionContext();
        demoController.ActionContext.HttpContext = new DefaultHttpContext();
        demoController.HttpContext.Session = new DummySession();
Run Code Online (Sandbox Code Playgroud)

DefaultHttpContext类由平台提供.DummySession可以是实现ISession类的简单类.这简化了很多事情,因为不再需要进行模拟.