English 中文(简体)
How do I Fake UpdateModel for ASP.Net MVC?
原标题:

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.

最佳回答

You re not using the FormCollection that you ve passed in to you action method. The reason you usually pass in a FormCollection is to aid in testing by breaking the UpdateModel dependency on the HttpConext.

All you need to do is change your UpdateModel line to:

UpdateModel(style, collection.ToValueProvider());

Once you ve done that you can forget about setting up your mock HttpContext. E.g. your test could now read like:

[Test]
public void Edit_GivenFormsCollection_CanPersistStyleChanges()
{
    //Blah

    var nameValueCollection = new NameValueCollection();
    InitFormCollectionWithSomeChanges(nameValueCollection, style);
    //Removed stuff

    controller.Edit(1, new FormCollection(nameValueCollection));

    //Blah
}

HTHs,
Charles

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签