Over a million developers have joined DZone.

Using Moq to mock ASP.NET MVC HttpContextBase

·

Here’s my little example about how to use Moq to mock HttpContextBase and it’s members to make controller tests pass. You can use this code when you are not allowed to use open-source or use-on-your-own-risk pieces of software that provide you this kind on initialization using built-in features. Also it is good exercise that introduces you how to solve mocking problems.

Here’s the simple example to get started.

var controller = new MyController();
 
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>();
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);
 
controller.ControllerContext = new ControllerContext(context.Object,
                                  new RouteData(), controller);

Same way you can also mock other members of HttpContextBase.

Topics:

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}