jqueryasp.net-mvcunit-testingjsontestability

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?


Solution

  • 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
        }
    });