Sunday, April 25, 2010

Mocking an MVC Controller in C# and Moq

When unit testing an MVC controller you will on occasions be required to mock out the controller context. The following code is the basis to allowing this.

namespace ProjectNamespace
{
public class FakeControllerContext
{
public ControllerContext ControllerContext { get; private set; }

private readonly Mock<ControllerBase> _mockOfControllerBase;
private readonly Mock<HttpContextBase> _mockOfHttpContextBase;
private readonly Mock<HttpSessionStateBase> _mockOfHttpSessionStateBase;

public FakeControllerContext()
{
_mockOfControllerBase = new Mock<ControllerBase>();
_mockOfHttpContextBase = new Mock<HttpContextBase>();
_mockOfHttpSessionStateBase = new Mock<HttpSessionStateBase>();

ControllerContext = new ControllerContext(_mockOfHttpContextBase.Object, new RouteData(), _mockOfControllerBase.Object);
}
}
}


Once this class has been set-up then you can set the context of your controller as follows: ~

var controller = new YourController() { ControllerContext = new FakeControllerContext().ControllerContext };

No comments: