Link to home
Start Free TrialLog in
Avatar of dyarosh
dyarosh

asked on

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

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
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dyarosh
dyarosh

ASKER

How do I go about getting the RedirectToRouteResult so I can check that it redirects to the correct page?
Avatar of dyarosh

ASKER

I was able to cast the result to RedirectToRouteResult and pull the data I needed.  Thank you for your help.