1

We would like to Unit test authentication for portions of our MVC5 web-app but it's not clear how we can test this for controllers/controller methods decorated by the [Authorize] attribute. Instantiating the controller and invoking that method seems to ignore that [Authorize] attribute.

Similarly, some controller methods (eg: AccountController's SignInAsync() method) end up referencing HttpContext and the Authentication property within it's object hierarchy (snippet below, standard MVC5 template code). This makes it hard to unit test properly.

So does anyone have some ideas or approaches on how to effectively test the authentication aspect of the MVC5 app? Seems like another layer is needed to simulate the HTTP req/resp (even if those req/resp don't traverse the network stack) ...

 1: private IAuthenticationManager AuthenticationManager
 2: {
 3:   get { HttpContext.GetOwinContext().Authentication; }
 4: }
 5: 
 6: private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 7: {
 8:    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
 9:    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
10:    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
11: }

1 Answer 1

1

The framework uses reflection to look for attributes on methods before it calls them, and executes methods in those attributes. When you call these methods directly, you're not doing that.. so therefore the attributes methods do not get called.

You could execute the same code to test for an attribute, and then call its methods.. but in general, you don't need to test framework provided functionality. You would only need to verify that the attribute is present, and configured correctly.

You would then use an integration test later in your process to ensure that the actual login process works correctly.

If you want an example of testing that the attribute is present, see here:

https://stackoverflow.com/a/670838/61164

If you have your own Authorization filter, then you should definitely test that. You can follow the advice here:

http://darioquintana.com.ar/blogging/2009/05/23/aspnet-mvc-testing-a-custom-authorize-filters/

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

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.