I am trying to unit test a controller action that uses UpdateModel but I am not correctly mocking the HttpContext. I keep getting the following exception:
System.InvalidOperationException: Previous method 'HttpRequestBase.get_Form();' requires a return value or an exception to throw.
To mock the HttpContext I am using some thing similar to what scott posted for Rhino mocks.
I added one method for what I thought would mock the 'HttpRequestBase.get_Form();'
public static void SetupRequestForm(this HttpRequestBase request, NameValueCollection nameValueCollection)
{
if (nameValueCollection == null)
throw new ArgumentNullException("nameValueCollection");
SetupResult.For(request.PathInfo).Return(string.Empty);
SetupResult.For(request.Form).Return(nameValueCollection);
}
Here is the unit test:
[Test]
public void Edit_GivenFormsCollection_CanPersistStyleChanges()
{
//in memory db setup omitted ...
var nameValueCollection = new NameValueCollection();
InitFormCollectionWithSomeChanges(nameValueCollection, style);
var httpContext = _mock.FakeHttpContext();
_mock.SetFakeControllerContext(controller, httpContext);
httpContext.Request.SetupRequestForm(nameValueCollection);
controller.Edit(1, new FormCollection(nameValueCollection));
var result = (ViewResult)controller.Edit(1);
Assert.IsNotNull(result.ViewData);
style = Style.GetStyle(1);
AsserThatModelCorrectlyPersisted(style);
}
The controller action under test:
[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
var campaign = Campaign.GetCampaign(id);
if (campaign == null)
return View("Error", ViewData["message"] = "Oops, could not find your requested campaign.");
if (!campaign.CanEdit(User.Identity.Name))
return View("Error", ViewData["message"] = "You are not authorized to edit this campaign style.");
var style = campaign.GetStyle();
//my problem child for tests.
UpdateModel(style);
if (!style.IsValid)
{
ModelState.AddModelErrors(style.GetRuleViolations());
return View("Edit", style);
}
style.Save(User.Identity.Name);
return RedirectToAction("Index", "Campaign", new { id });
}
I will accept any answer that correctly modifies my SetupRequestForm, unit test, or posts an example on how to use the Test helpers in the MVCContrib project to achieve the same goal.