6

Let's say you have a profile page that can only be accessed by the owner of that profile. This profile page is located at:

User/Profile/{userID}

Now, I imagine in order to prevent access to this page by other users, you could structure your UserController class's Profile function to check the current session's identity:

HttpContext.Current.User.Identity.Name

If the id matches the one in the url, then you proceed. Otherwise you redirect to some sort of error page.

My question is how do you unit test something like this? I'm guessing that you need to use some sort of dependency injection instead of the HttpContext in the controller to do the check on, but I am unclear what the best way to do that is. Any advice would be helpful.

4 Answers 4

1

The link above is a good one. I would also add that instead of programmatically checking the User.Identity.Name value, you should use the Authorize attributes as outlined in the article:

http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx

Sign up to request clarification or add additional context in comments.

Comments

1

I ended up going with the "UserNameFilter" shown in Kazi Manzur's blog post. Works like a charm and easy to unit test.

Comments

1

You can probably do it by using a fake for the controller context. Check out this article: http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

Comments

0

This is where mocking comes in, with a fake HttpContext.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.