Faking the WebApi User

I needed to unit test a WebAPI call in my MVC 4 application that checks the user's role. I'm doing this in my MVC controllers with the following code using FakeItEasy (I should do a post on that sometime):

this.UserPrincipalFake = A.Fake(); A.CallTo(() => this.UserPrincipalFake.Identity).Returns(A.Fake()); A.CallTo(() => this.UserPrincipalFake.Identity.Name).Returns("username"); this.HttpContextBaseFake = A.Fake(); this.HttpContextBaseFake.User = this.UserPrincipalFake; this.HttpSessionStateBaseFake = new FakeHttpSessionState(); A.CallTo(() => this.HttpContextBaseFake.Session).Returns(this.HttpSessionStateBaseFake); this.RequestContextFake = A.Fake(); this.RequestContextFake.HttpContext = this.HttpContextBaseFake; this.Controller.ControllerContext = new ControllerContext(this.RequestContextFake, this.Controller);

The problem I was having with WebAPI (and I can't find what I need after searching on the web) is that the WebApi this.Controller.ControllerContext is a HTTPControllerContext and different from MVC and it's Request is an HttpRequestMessage, so I can't use the same setup. I wasn’t able to completely figure out the full mocking, but I was able to get the User faked by using the answer from this Stackoverflow question. The simple approach is to set the Thread.CurrentPrincipal. Here is my test. IsInRole is an extension method I defined in a different spot.

[TestMethod, TestCategory("UiApiController")] public void Delete_SuperAdmin_Calls_Delete() { // Arrange // http://stackoverflow.com/questions/15413754/set-user-property-for-an-apicontroller-in-unit-test Thread.CurrentPrincipal = this.UserPrincipalFake; A.CallTo(() => this.UserPrincipalFake.IsInRole(Authentication.SUPER_ADMIN_ROLE_NAME)).Returns(true); A.CallTo(() => this.UserPrincipalFake.Identity.IsAuthenticated).Returns(true);

// Act
this.Controller.Delete(1);

// Assert
A.CallTo(() => this.LayoutManagerFake.Delete(A<Layout>.That.Matches(l => l.LayoutId == 1), true)).MustHaveHappened();

}

This article is part of the GWB Archives. Original Author: Aligned

New on Geeks with Blogs