views:

53

answers:

1

when unit testing a asp.net controller, don't you have to somehow mock the httpcontextbase?

All my controllers inherit from a custom controller class that I wrote (it just adds some common properties to the original controller class). So its like:

public class MyController : Controller
{
    protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext context)
    {
         // look for a specific cookie
    }

}

so really want to start unit testing my controllers, just unsure how I go about mocking the controller classes and the httpcontext that goes with it.

+1  A: 

Here's an example of how you can use Moq to set up a Mock HttpContextBase:

var httpCtxStub = new Mock<HttpContextBase>();

var controllerCtx = new ControllerContext();
controllerCtx.HttpContext = httpCtxStub.Object;

sut.ControllerContext = controllerCtx;

// Exercise and verify the sut

where sut represents the System Under Test (SUT), i.e. the Controller you wish to test.

Mark Seemann