C# 单元测试Web Api控制器假冒ApicController。具有自定义标识的用户不';行不通

C# 单元测试Web Api控制器假冒ApicController。具有自定义标识的用户不';行不通,c#,unit-testing,asp.net-mvc-4,asp.net-web-api,C#,Unit Testing,Asp.net Mvc 4,Asp.net Web Api,我目前正在使用WebAPI v5.2.2,并且正在为其中一个控制器编写单元测试代码。我遇到的问题发生在ApiController.User部分 我有用户实现的IIdentity界面的自定义标识: public class CustomIdentity : IIdentity { //Constructor and methods } CustomIdentity是在正常使用情况下在HttpRequest中设置的。但是因为我只是在单元测试中测试查询功能,所以我只是调用了控制器及其方法,而

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

我有用户实现的IIdentity界面的自定义标识:

public class CustomIdentity : IIdentity
{
    //Constructor and methods
}
CustomIdentity是在正常使用情况下在HttpRequest中设置的。但是因为我只是在单元测试中测试查询功能,所以我只是调用了控制器及其方法,而不是发送请求

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

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;
}
但是,我从两次尝试中都得到了这个错误:

对象引用未设置为对象的实例

我发现线程中的用户标识仍然为空

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

你说

CustomIdentity是在正常使用情况下在HttpRequest中设置的

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

请检查此处的示例


你的第一次尝试对我有用。异常被抛出的确切位置是哪里?您可以尝试controller.User=newclaimsprincipal(newcustomidentity(User));能否显示引发错误的操作之一的片段?异常被抛出的具体位置?您的第一个测试对我也有效。但是由于我们不知道控制器的操作中发生了什么,因此无法确定抛出的是什么异常控制器的操作只包含Linq查询,并且异常是在controller.User=new ClaimsPrincipal(…)之后抛出的。我也不知道元数据文件中出了什么问题。我将请求与配置一起附加到控制器。但我尝试了@ChrisS注释的建议,即controller.User=newclaimsprincipal(newcustomidentity(User));现在一切正常。此外,很难附加异常引发位置,因为它都发生在controller内的元数据中;谢谢你的帮助。
[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
}