Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
MvcMockHelpers.cs - Helper Utility for Mocking MVC3 Controllers with Moq.
using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;
/// <summary>
/// This helper class can be used to set up Moq mocks of MVC3 controllers.
/// Slightly modified from the original version from Scott Hanselman's blog:
/// </summary>
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.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.SetupProperty(ctx => ctx.User);
return context.Object;
public static HttpContextBase FakeHttpContext(string url)
var context = FakeHttpContext();
return context;
public static void SetFakeControllerContext(this Controller controller, string requestUrl = "~/Nowhere/")
var httpContext = FakeHttpContext(requestUrl);
var requestContext = new RequestContext(httpContext, new RouteData());
var context = new ControllerContext(requestContext, controller);
controller.ControllerContext = context;
controller.Url = new UrlHelper(requestContext);
private static string GetUrlFileName(string url)
return url.Contains("?") ? url.Substring(0, url.IndexOf("?")) : url;
private static NameValueCollection GetQueryStringParameters(string url)
if (url.Contains("?"))
var parameters = new NameValueCollection();
var parts = url.Split("?".ToCharArray());
var keys = parts[1].Split("&".ToCharArray());
foreach (var key in keys)
var part = key.Split("=".ToCharArray());
parameters.Add(part[0], part[1]);
return parameters;
return null;
public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod)
.Setup(req => req.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.Setup(req => req.QueryString)
mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
mock.Setup(req => req.PathInfo)
mock.SetupGet(x => x.Url).Returns(new Uri(url.Replace("~/", "")));

rally25rs commented Jan 8, 2012

Sample Usage:

var controller = new SomeController();

This will set up the HttpContext, RequestContext, and UrlHelper inside the controller, so that the controller code can still execute.


rally25rs commented Jan 8, 2012

Also allows the user Principal to be set on the HttpContext:

var controller = new SomeController();
controller.HttpContext.User = new GenericPrincipal(new GenericIdentity("username"), new string[0]);

I'm new at this... How do I integrate this into the Controller? Are you adding that static method to the controller?

Added a modified version of this that creates/returns a dictionary of all mocked objects in a controller
Gist can be found here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment