设置用户属性的单元测试的ApiController(Set User property for an

2019-08-17 14:07发布

对于ApiController我的单元测试使用了一些助手方法来实例化控制器:

public static ResourcesController SetupResourcesController(HttpRequestMessage request, IResourceMetadataRepository repo, IUnitOfWorkService unitOfWorkService)
{
    var config = new HttpConfiguration();
    var defaultRoute = config.Routes.MapHttpRoute(RouteNames.DefaultApi , "api/{controller}/{id}");
    var routeData = new HttpRouteData(defaultRoute, new HttpRouteValueDictionary { { "controller", "resources" } });

    var resourcesController = new ResourcesController(repo, unitOfWorkService)
    {
        ControllerContext = new HttpControllerContext(config, routeData, request),
        Request = request
    };
    resourcesController.Request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);
    resourcesController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

    // Compilation fail: The Property 'System.Web.Http.ApiController.User' has no setter.
    resourcesController.User = myStubUserPrincipal;

    return resourcesController;
}

我的问题是:如何设置用户属性控制器?

我试过了:

request.Properties.Add("MS_UserPrincipal", myStubUserPrincipal);

但是,这并不工作,要么(在resourcesController.User财产保持为空)。

Answer 1:

设置Thread.CurrentPrincipal ,这将初始化User自动控制器属性。

对于看到这个答案,但不知道如何设置人CurrentPrincipal : 此代码是从MSDN中提取。

Thread.CurrentPrincipal = new GenericPrincipal
(
   new GenericIdentity("Bob", "Passport"),
   new[] {"managers", "executives"}
);


Answer 2:

一个清洁的方法是嘲笑走IPrincipalHttpRequestContext ,例如使用起订量:

var userMock = new Mock<IPrincipal>();
userMock.Setup(p => p.IsInRole("admin")).Returns(true);
userMock.SetupGet(p => p.Identity.Name).Returns("tester");
userMock.SetupGet(p => p.Identity.IsAuthenticated).Returns(true);

var requestContext = new Mock<HttpRequestContext>();
requestContext.Setup(x => x.Principal).Returns(userMock.Object);

var controller = new ControllerToTest()
{
    RequestContext = requestContext.Object,
    Request = new HttpRequestMessage(),
    Configuration = new HttpConfiguration()
};


文章来源: Set User property for an ApiController in Unit Test