Friday, February 4, 2011

Best way to unit test ASP.NET MVC action methods that use BindingHelperExtensions.UpdateFrom?

In handling a form post I have something like

    public ActionResult Insert()
    {
        Order order = new Order();
        BindingHelperExtensions.UpdateFrom(order, this.Request.Form);

        this.orderService.Save(order);

        return this.RedirectToAction("Details", new { id = order.ID });
    }

I am not using explicit parameters in the method as I anticipate having to adapt to variable number of fields etc. and a method with 20+ parameters is not appealing.

I suppose my only option here is mock up the whole HttpRequest, equivalent to what Rob Conery has done. Is this a best practice? Hard to tell with a framework which is so new.

I've also seen solutions involving using an ActionFilter so that you can transform the above method signature to something like

[SomeFilter] public Insert(Contact contact)

  • Wrap it in an interface and mock it.

    From Matt Hinze
  • Use NameValueDeserializer from http://www.codeplex.com/MVCContrib instead of UpdateFrom.

  • I'm now using ModelBinder so that my action method can look (basically) like:

        public ActionResult Insert(Contact contact)
        {
    
            if (this.ViewData.ModelState.IsValid)
            {
                this.contactService.SaveContact(contact);
    
                return this.RedirectToAction("Details", new { id = contact.ID });
            }
            else
            {
                return this.RedirectToAction("Create");
            }
        }
    

0 comments:

Post a Comment