26

我对 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 属性保持为空)。

4

2 回答 2

37

Set the Thread.CurrentPrincipal, and that will initialize the User property in the controller automatically.

For people that see this answer, but have no idea how to set CurrentPrincipal.: This code is extracted from MSDN.

Thread.CurrentPrincipal = new GenericPrincipal
(
   new GenericIdentity("Bob", "Passport"),
   new[] {"managers", "executives"}
);
于 2013-03-15T15:25:46.897 回答
13

一种更清洁的方法是模拟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()
};
于 2016-08-01T14:00:19.340 回答