I often find it convenient to test Asp.Net MVC application on the controllers. One thing I find myself repeat over and over again is mocking the HttpContext and setting Request.QueryString and Request.Form values. It brings great value to the tests being able to test how the model binders behave given certains posted values or how the controller logic reacts to querystring parameters.
Most of the time I use Moq and here is some code to achieve the mocking:
[Test]
public void Some_Clever_Test()
{
var querystring = new NameValueCollection {{"something", "got_value"}};
var formvalues = new NameValueCollection {{"pageid", "1"}};
ControllerContext context = TestHelpers.GetControllerContext("GET", querystring, formvalues);
var controller = GetController(context);
ActionResult actionResult = controller.Index();
var model = actionResult.Model <productpageviewmodel>(); // A nice helper I found somewhere
Assert.That(model, Is.Not.Null); // Perhaps a more clever assert here...
}
TestHelpers.GetControllerContext looks like this:
public static class TestHelpers
{
public static ControllerContext GetControllerContext(string httpmethod, NameValueCollection querystring = null, NameValueCollection form = null)
{
var user = new Mock <iprincipal>();
user.Setup(u => u.Identity.Name).Returns("testid");
var request = new Mock <httprequestbase>();
request.Setup(r => r.HttpMethod).Returns(httpmethod);
request.Setup(r => r.PathInfo).Returns(string.Empty);
var mockHttpContext = new Mock<httpcontextbase>();
mockHttpContext.Setup(c => c.Request).Returns(request.Object);
mockHttpContext.Setup(c => c.User).Returns(user.Object);
mockHttpContext.Setup(c => c.Request.QueryString).Returns(querystring);
mockHttpContext.Setup(c => c.Request.Form).Returns(form);
return new ControllerContext(mockHttpContext.Object, new RouteData(),
new Mock<controllerbase>().Object);
}
}
This can be extended to be a bit more clever but its a start.
I just signed up to your blogs rss feed. Will you post more on this subject?
It is very likely that I will blog more about mocking