Geeks With Blogs

News Please visit me at my new blog!!

profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
more about the Gospel
And then listen to Francis Chan speaking at LifeLight in SD.



Programming and Learning from SD

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<IPrincipal>();
A.CallTo(() => this.UserPrincipalFake.Identity).Returns(A.Fake<IIdentity>());
A.CallTo(() => this.UserPrincipalFake.Identity.Name).Returns("username");
this.HttpContextBaseFake = A.Fake<HttpContextBase>();
this.HttpContextBaseFake.User = this.UserPrincipalFake;
this.HttpSessionStateBaseFake = new FakeHttpSessionState();
A.CallTo(() => this.HttpContextBaseFake.Session).Returns(this.HttpSessionStateBaseFake);
this.RequestContextFake = A.Fake<RequestContext>();
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();
}
Posted on Wednesday, June 5, 2013 10:29 AM MVC , WebApi , Unit Testing , BDD , Mocking | Back to top


Comments on this post: Faking the WebApi User

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Aligned | Powered by: GeeksWithBlogs.net