开发者

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 dat开发者_运维百科a from a $.ajax() call?


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", "");


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜