StuperUser
StuperUser

Reputation: 10850

How to test Controller Action that uses JSON string from Request.Form?

I have an Action that gets JSON data from Request.Form[0] and has calls into domain objects.

I am testing this method, but it seems impossible to set Request.Form.

I could extract the method to another that takes the string it returns, but that would just be a one line method and the Action would still be untested.

Is there a method to test this or another, more testable method to get the JSON data from a $.ajax() call?

Upvotes: 1

Views: 896

Answers (2)

StuperUser
StuperUser

Reputation: 10850

It's possible to pass a strongly typed string parameter writing it into the method, by adding it as a parameter

public JsonResult ActionName(string paramName)

and including it in the data:

var dataVar = getDataVar();
$.ajax({
    url: '/Controller/ActionName'
    , type: 'post'
    , data: { paramName: dataVar }
    , dataType: 'json'

    , success: function (returnJSON) {
    }
    , error: function (XMLHttpRequest, textStatus, errorThrown) {
    //error handle in here
    }
});

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038790

Personally I Use MVCContrib TestHelper to unit test my controller actions. It makes things very fun and easy.

So in your case assuming the following controller (disclaimer: absolutely never write something like this in a real application, it's just an example here, in a real world application controller actions should never fetch stuff from Request.Form, they should use strongly typed action parameters and leave the default model binder do the parsing, etc...):

public class MyViewModel
{
    public string SomeProperty { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var json = Request.Form[0];
        var model = new JavaScriptSerializer().Deserialize<MyViewModel>(json);
        return View(model);
    }
}

you could test it like this:

// arrange
var builder = new TestControllerBuilder();
var sut = new HomeController();
builder.InitializeController(sut);
builder.Form.Add("foo", "{ someProperty: 'some value' }");

// act
var actual = sut.Index();

// assert
actual
    .AssertViewRendered()
    .WithViewData<MyViewModel>()
    .SomeProperty
    .ShouldEqual("some value", "");

Upvotes: 2

Related Questions