c# – 单元测试Web Api控制器伪造ApiController.User与自定义标识不起作用

我目前正在使用Web API v5.2.2,我正在为其中一个控制器编写单元测试代码.我遇到的问题发生在ApiController.User部分.

我有一个用户实现的IIdentity接口的自定义标识:

public class CustomIdentity : IIdentity
{
    //Constructor and methods
}

正常用法中的HttpRequest中设置了CustomIdentity.但由于我只测试单元测试中的查询功能,我只是调用控制器及其方法而不是发送请求.

因此,我必须将用户标识插入到线程中,我尝试了以下方法:

var controller = new AccountsController(new AccountUserContext());

第一次尝试:

controller.User = new ClaimsPrincipal(new GenericPrincipal(new CustomIdentity(user), roles.Distinct().ToArray()));

第二次尝试:

IPrincipal principal = null;

principal = new GenericPrincipal(new CustomIdentity(user), roles.Distinct().ToArray());

Thread.CurrentPrincipal = principal;

if (HttpContext.Current != null)
{
    HttpContext.Current.User = principal;
}

但是,我从这两次尝试中得到了这个错误:

Object reference not set to an instance of an object.

我发现用户身份在线程中保持为空.

以前有人试过这种方法吗?谢谢你的建议!

最佳答案 你说

The CustomIdentity was set in the HttpRequest in normal usage.

您是否在组装测试时向控制器附加请求?

在这里查看示例

Unit Testing Controllers in ASP.NET Web API 2

[TestMethod]
public void QueryAccountControllerTest()
{
    // Arrange
    var user = "[Username Here]"
    var controller = new AccountsController(new AccountUserContext());
    //Set a fake request. If your controller creates responses you will need tis
    controller.Request = new HttpRequestMessage { 
        RequestUri = new Uri("http://localhost/api/accounts") 
    };        
    controller.Configuration = new HttpConfiguration();
    controller.User = new ClaimsPrincipal(new CustomIdentity(user));

    // Act
    ... call action

    // Assert
    ... assert result
}
点赞