0

Background : We are using MVC4 and using WIF for Claims/Authorization. We are using Moq/MvcContrib for Mockup Objects. I have looked here and created the MockIdentity and MockPrincipal Objects - do I need them?

Goal : I have a controller class that has a class level attribute that only allows users with 'Manager' claim to access the actions. I want to create mock users and test to see if anyone that doesn't have 'Manager' claim can access the actions or not.

I get the mock concept but I have only dealt with the data objects mocking and having a tough time figuring out what plugins/classes/methods/setups I need in place to do what I need to do.

Thanks in advance.

Community
  • 1
  • 1
Pete
  • 169
  • 2
  • 14
  • Why would you test this? All you would be verifying is MVC's own infrastructure. Why is that valuable to your app? It'd be different if your logic (not MVC) was influenced by the presence of the Manager claim. Then a unit test would make sense and mocking the Principal, etc. would be necessary (if you are calling IPrincipal.IsInRole() for example). – Eugenio Pace Apr 30 '12 at 20:26

1 Answers1

3

I want to create mock users and test to see if anyone that doesn't have 'Manager' claim can access the actions or not.

No, you don't. You just want to pass users to that attribute you wrote and test that sets the filterContext.Result correctly. That's it. You don't need to test that System.Web.Mvc works. Single unit under test!

Presumably your attribute is an AuthorizeAttribute, correct? So you need to test OnAuthorization(AuthorizationContext).

Disclaimer: I haven't used moq in a while, but your code would presumably look generally like this:

var user = new Mock<IPrincipal>();
user.Setup(/* whatever you need to look at */);

var authContext = new Mock<AuthorizationContext>();
authContext.Setup(ac => ac.HttpContext.User).Returns(user);

var myAttribute = new RequireManagerAttribute();
myAttribute.OnAuthorization(authContext);

authContext.VerifySet(ac => ac.Result = /* whatever you expect */);
bhamlin
  • 5,177
  • 1
  • 22
  • 17
  • Thanks, I will try that and report back... Can you please look at the SO sample and tell me why the OP is doing what he is doing? Also, When do I need MvcContrib? – Pete Apr 29 '12 at 15:45
  • MvcContrib offers some help getting a fully initialized controller built. In this case, since you're just testing the attribute, you don't need that. As for what that guy is doing - using static methods like Roles.AddUserToRole makes unit testing really difficult. Another reason not to avoid them. – bhamlin Apr 29 '12 at 19:29