How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6

后端 未结 4 2225

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 o

4条回答
  •  不知归路
    2020-12-25 09:06

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

提交回复
热议问题