xunit-如何在单元测试中获取HttpContext.User.Identity

时间:2019-11-20 09:16:22

标签: c# unit-testing .net-core xunit

我向我的控制器添加了一个方法,以从HttpContext中的JWT令牌中获取用户ID。在我的单元测试中,HttpContext null ,因此出现异常。

我该如何解决问题?有没有办法HttpContext起订量?

这是将用户吸引到我的基本控制器中的方法

protected string GetUserId()
{
    if (HttpContext.User.Identity is ClaimsIdentity identity)
    {
        IEnumerable<Claim> claims = identity.Claims;
        return claims.ToList()[0].Value;
    }

    return "";
}

我的一个测试看起来像这样

[Theory]
[MemberData(nameof(TestCreateUsergroupItemData))]
public async Task TestPostUsergroupItem(Usergroup usergroup)
{
    // Arrange
    UsergroupController controller = new UsergroupController(context, mapper);

    // Act
    var controllerResult = await controller.Post(usergroup).ConfigureAwait(false);

    // Assert
    //....
}

2 个答案:

答案 0 :(得分:5)

在这种特殊情况下,确实不需要模拟HttpContext

使用DefaultHttpContext并设置完成测试所需的成员

例如

[Theory]
[MemberData(nameof(TestCreateUsergroupItemData))]
public async Task TestPostUsergroupItem(Usergroup usergroup) {
    // Arrange

    //...

    var identity = new GenericIdentity("some name", "test");
    var contextUser = new ClaimsPrincipal(identity); //add claims as needed

    //...then set user and other required properties on the httpContext as needed
    var httpContext = new DefaultHttpContext() {
        User = contextUser;
    };

    //Controller needs a controller context to access HttpContext
    var controllerContext = new ControllerContext() {
        HttpContext = httpContext,
    };
    //assign context to controller
    UsergroupController controller = new UsergroupController(context, mapper) {
        ControllerContext = controllerContext,
    };

    // Act
    var controllerResult = await controller.Post(usergroup).ConfigureAwait(false);

    // Assert
    ....
}

答案 1 :(得分:1)

首先,我建议您使用IHttpContextAccessor访问HttpContext并通过Dependency Injection进行注入,而不要直接使用HttpContext。您可以阅读此Microsoft文档,以了解IHttpContextAccessor的用法和注入。

使用以上代码,您的代码将如下所示以注入IHttpContextAccessor

private IHttpContextAccessor  httpContextAccessor;
public class UsergroupController(IHttpContextAccessor httpContextAccessor, ...additional parameters)
{
   this.httpContextAccessor = httpContextAccessor;
   //...additional assignments
}

一旦注入IHttpContextAccessor,您就可以以this.httpContextAccessor.HttpContext.User.Identity的身份访问

因此GetUserId应该更改为

protected string GetUserId()
{
    if (this.httpContextAccessor.HttpContext.User.Identity is ClaimsIdentity identity)
    {
        IEnumerable<Claim> claims = identity.Claims;
        return claims.ToList()[0].Value;
    }

    return "";
}

通过上述更改,现在您可以轻松注入IHttpContextAccessor的模拟物以进行单元测试。您可以使用以下代码创建模拟:

private static ClaimsPrincipal user = new ClaimsPrincipal(
                        new ClaimsIdentity(
                            new Claim[] { new Claim("MyClaim", "MyClaimValue") },
                            "Basic")
                        );


private static Mock<IHttpContextAccessor> GetHttpContextAccessor()
{
        var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
        httpContextAccessorMock.Setup(h => h.HttpContext.User).Returns(user);
        return httpContextAccessorMock;
}

通过上述设置,可以在测试方法中实例化IHttpContextAccessor的对象时注入UsergroupController的模拟物。