2

How can i write test case for action filters? I am using forms authentication. I have base controller decorated with RequiresAuthentication action filter. When i execute the controller's test case, i am not getting the loggedin user's data from the cookies.

I am using Moq; does it provide a way to achieve my goal?

2
  • Probably duplicate of stackoverflow.com/questions/366388/… Commented Dec 15, 2010 at 12:26
  • no this is not the one that i am looking for. I am looking for something where i can use Moq framework to create fake htttpcontext. Commented Dec 16, 2010 at 4:59

1 Answer 1

2

This blog post from Scott Hanselmann covers MvcMockHelpers including FakeHttpContext for different mocking frameworks among others also Moq:

using System;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Specialized;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;

namespace UnitTests
{
    public static class MvcMockHelpers
    {
        public static HttpContextBase FakeHttpContext()
        {
            var context = new Mock<httpcontextbase>();
            var request = new Mock<httprequestbase>();
            var response = new Mock<httpresponsebase>();
            var session = new Mock<httpsessionstatebase>();
            var server = new Mock<httpserverutilitybase>();

            context.Expect(ctx => ctx.Request).Returns(request.Object);
            context.Expect(ctx => ctx.Response).Returns(response.Object);
            context.Expect(ctx => ctx.Session).Returns(session.Object);
            context.Expect(ctx => ctx.Server).Returns(server.Object);

            return context.Object;
        }

        public static HttpContextBase FakeHttpContext(string url)
        {
            HttpContextBase context = FakeHttpContext();
            context.Request.SetupRequestUrl(url);
            return context;
        }

        public static void SetFakeControllerContext(this Controller controller)
        {
            var httpContext = FakeHttpContext();
            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
        }

        static string GetUrlFileName(string url)
        {
            if (url.Contains("?"))
                return url.Substring(0, url.IndexOf("?"));
            else
                return url;
        }

        static NameValueCollection GetQueryStringParameters(string url)
        {
            if (url.Contains("?"))
            {
                NameValueCollection parameters = new NameValueCollection();

                string[] parts = url.Split("?".ToCharArray());
                string[] keys = parts[1].Split("&".ToCharArray());

                foreach (string key in keys)
                {
                    string[] part = key.Split("=".ToCharArray());
                    parameters.Add(part[0], part[1]);
                }

                return parameters;
            }
            else
            {
                return null;
            }
        }

        public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod)
        {
            Mock.Get(request)
                .Expect(req => req.HttpMethod)
                .Returns(httpMethod);
        }

        public static void SetupRequestUrl(this HttpRequestBase request, string url)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            if (!url.StartsWith("~/"))
                throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\".");

            var mock = Mock.Get(request);

            mock.Expect(req => req.QueryString)
                .Returns(GetQueryStringParameters(url));
            mock.Expect(req => req.AppRelativeCurrentExecutionFilePath)
                .Returns(GetUrlFileName(url));
            mock.Expect(req => req.PathInfo)
                .Returns(string.Empty);
        }
    }
}

Another good resource for ASP.NET MVC test helpers is the MvcContrib project on CodePlex.

After you have a FakeHttpContext you can test your action filter:

var context = new ActionExecutedContext();
context.HttpContext = MvcMockHelpers.FakeHttpContext();
context.Result = new EmpytResult(); // or whatever the default result should be

var filter = new MyCustomAttribute();
filter.OnActionExecuted(context);

Assert.True(context.Result is EmpytResult);
...
Sign up to request clarification or add additional context in comments.

1 Comment

Anyone know why it needs a virtual URL; is there a good reason to enforce this?

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.