xunit - 如何在单元测试中获取 HttpContext.User.Identity [英] xunit - how to get HttpContext.User.Identity in unit tests

查看:20
本文介绍了xunit - 如何在单元测试中获取 HttpContext.User.Identity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向控制器添加了一个方法,以从 HttpContext 中的 JWT 令牌中获取用户 ID.在我的单元测试中,HttpContextnull,所以我得到一个异常.

I added a method to my controllers to get the user-id from the JWT token in the HttpContext. In my unit tests the HttpContext is null, so I get an exception.

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

How can I solve the problem? Is there a way to moq the HttpContext?

这是在我的基本控制器中获取用户的方法

Here is the method to get the user in my base controller

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

    return "";
}

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

One of my tests look like this

[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
    //....
}

推荐答案

在这种特殊情况下,确实没有必要模拟 HttpContext.

There really is no need to have to mock the HttpContext in this particular case.

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

Use the DefaultHttpContext and set the members necessary to exercise the test to completion

例如

[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
    ....
}

这篇关于xunit - 如何在单元测试中获取 HttpContext.User.Identity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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