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

时间:2016-03-15 14:45:18

标签: c# unit-testing asp.net-mvc-4 asp.net-web-api

我目前正在使用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;
}

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

  

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

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

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

1 个答案:

答案 0 :(得分:2)

你说

  

在正常使用情况下,在HttpRequest中设置了CustomIdentity。

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

查看此处的示例

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
}
相关问题