views:

946

answers:

2

I'm trying to unit test a page in my ASP.NET MVC application that, when posted to, will delete a user's item. I want to restrict this page so that it can only be posted to by the owner of said item. Originally, I wanted to just stick a quick check in the controller that checked if the HttpContext.Current.User.Identity.Name is equal to the owner of the item, but I quickly realized that unit testing this would be difficult.

Should I create an interface that provides a way to access the current logged-in user's name?

+2  A: 

I use Thread.CurrentPrincipal.Identity.Name. It's trivial to create a GenericPrincipal for a unit test and attach it.

Craig Stuntz
+4  A: 

The last line of your question is probably the quickest solution, however, I don't think you need to create the interface, HttpContext.Current.User is already an IPrincipal and HttpContext.Current.User.Identity is already an IIdentity.

If your checking logic uses either of those interfaces, the controller can be mocked to pass an IIdentity that you create instead of the HttpContext.Current.User.Identity

Hope that helps!

Zachary Yates