27

My unit tests for an ApiController uses some helpers methods to instantiate the controller:

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;
}

My question is: how to set the User property for the controller?

I've tried:

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

But this doesn't work either (the resourcesController.User property remains null).

2 Answers 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"}
);
8
  • Thanks Pablo! Seems too simple to be true but yes; setting the Thread.CurrentPrincipal property within my test setup code did the trick!
    – JTech
    Commented Mar 19, 2013 at 15:59
  • Great! I was searching on how to mock/fake everything and this is a simple way to do it.
    – AlignedDev
    Commented Jun 5, 2013 at 15:27
  • 3
    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"}); msdn.microsoft.com/en-us/library/… Add this to your answer if you want.
    – ruffen
    Commented Sep 19, 2013 at 12:24
  • 1
    I tried to use this method in my unit tests for Web Api 2, but the User property is always null.
    – ozstudent
    Commented Jun 11, 2014 at 5:39
  • 4
    You can also set it directly on the controller like so: resourcesController.RequestContext.Principal = new ...
    – Nebula
    Commented Sep 16, 2015 at 9:54
13

A cleaner way would be to mock away IPrincipal and HttpRequestContext, for example using Moq:

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()
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.