Solved

How to Assert the Result property of AuthorizationContext in MVC unit testing

Posted on 2014-03-19
3
988 Views
Last Modified: 2014-03-20
I am trying to do unit testing of an Authorize attribute.  I am using Moq to mock the HttpContext that is a required parameter of the AuthorizeCore method.  The only thing I have in the AuthorizeCore method is a check if the HttpContext.Session is null to return false.  This is working but because it is false, there is a RedirectController that redirects to a page that says the user is Unauthorized.

The problem I have is in my Unit Test I don't know how to test the authorizationContext.Result.

authorizationContext.Result displays the following when I print it in the Command Window:
[System.Web.Mvc.RedirectToRouteResult]: {System.Web.Mvc.RedirectToRouteResult}

If I hover over the authorizationContext.Result in Debug mode, I can drill down and get to Values that tell me the controller and action but I can't figure out how to access them.  (See attached Screen Shot).

So basically what I want is the correct syntax for doing an Assert that shows the test passed.

Here is the Authorize Attribute Code:
using System.Web;
using System.Web.Mvc;


namespace AppCatalog.Models
{

    public class AuthUser : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.Session == null)
                return false;

            bool authorized = false;
            return authorized;

        }


        private class RedirectController : Controller
        {
            public ActionResult RedirectToSomewhere()
            {
                return RedirectToAction("Authorize", "Error");
            }
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
           
            filterContext.Result = (new RedirectController()).RedirectToSomewhere();
        }
    }
  
}

Open in new window


Here is my Test:
namespace AppCatalog.Tests
{
    [TestClass]
    public class AuthorizeTest
    {
        private AuthorizeAttribute attribute;
        private AuthorizationContext authorizationContext;

        internal class FakeController : Controller
        {
            public ActionResult Nothing()
            {
                return new EmptyResult();
            }
        }

        private void SetupSession(bool isAuthorized = true)
        {
            var mockContext = Mock.Get(authorizationContext.HttpContext);
            var mockSession = new Mock<HttpSessionStateBase>();
            mockSession.SetupGet(x => x["IsAuthenticated"]).Returns(isAuthorized);

            // Return the mock.
            mockContext.SetupGet(x => x.Session).Returns(mockSession.Object);
        }

        private void Authorize()
        {
            attribute.OnAuthorization(authorizationContext);
        }

        [TestInitialize]
        public void TestSetup()
        {
            attribute = new AuthUser();

            var controller = new FakeController();
            var server = new Mock<HttpServerUtilityBase>(MockBehavior.Loose);
            var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
            var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
            request.Setup(r => r.UserHostAddress).Returns("127.0.0.1");
            var session = new Mock<HttpSessionStateBase>();
            session.Setup(s => s.SessionID).Returns(Guid.NewGuid().ToString());
            var context = new Mock<HttpContextBase>(MockBehavior.Strict);
            context.SetupGet(c => c.Items).Returns(new Mock<IDictionary>().Object);
            context.SetupGet(c => c.Request).Returns(request.Object);
            context.SetupGet(c => c.Response).Returns(response.Object);
            context.SetupGet(c => c.Server).Returns(server.Object);
            context.SetupGet(c => c.Session).Returns(session.Object);

            ControllerContext ctx = new ControllerContext();
            ctx.HttpContext = context.Object;

            authorizationContext = new AuthorizationContext();
            authorizationContext.Controller = controller;
            authorizationContext.HttpContext = ctx.HttpContext;

            var controllerDescriptor = new ReflectedControllerDescriptor(typeof(FakeController));
            var method = typeof(FakeController).GetMethod("Nothing");
            authorizationContext.ActionDescriptor = new ReflectedActionDescriptor(method, "Nothing", controllerDescriptor);
        }

        [TestMethod]
        public void FailsWhenSessionIsNull()
        {
            // Arrange
            Mock.Get(authorizationContext.HttpContext).SetupGet(x => x.Session).Returns((HttpSessionStateBase)null);

            // Act
            Authorize();

            // Assert
            Assert.AreEqual("Authorize", authorizationContext.Result.RouteValues.Values[0]);
            //Assert.AreSame(typeof(System.Web.Mvc.RedirectToRouteResult), authorizationContext.Result);
            //Assert.AreSame("<System.Web.Mvc.RedirectToRouteResult (System.Web.Mvc.RedirectToRouteResult)>", authorizationContext.Result);
        }
    }
}

Open in new window


The Assert lines that are commented out are my different attempts to get something working.  The current Assert line doesn't compile because of an error on RouteValues that is basically saying it doesn't exist.
AuthorizationContext.fw.png
0
Comment
Question by:dyarosh
  • 2
3 Comments
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 39942467
What are you looking to test with the AuthorizationContext.Result, which is an ActionResult?  The ActionResult is an abstract base class, so you would need to get the concrete result:

    ContentResult
    EmptyResult
    FileResult
    HttpStatusCodeResult
    JavaScriptResult
    JsonResult
    RedirectResult
    RedirectToRouteResult
    ViewResultBase
0
 

Author Comment

by:dyarosh
ID: 39943555
How do I go about getting the RedirectToRouteResult so I can check that it redirects to the correct page?
0
 

Author Closing Comment

by:dyarosh
ID: 39943606
I was able to cast the result to RedirectToRouteResult and pull the data I needed.  Thank you for your help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now