开发者

Posting JSON to ASP.NET MVC 3.0 RC Controller and Unit Testing

Within MVC3 3 we can post a JSON based request to an MVC controller and it will automatically bind the result. I've been banging my head on how to unit test this properly and was hoping the experts here could put me on the right path.

Example of a simple jquery post with a json result can be found in the preview blog post: http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx

Within mvc 2 I could do create a simple unit test like this:

        // setup
        FormCollection formfakey = new FormCollection
        {
            {"address1", "123 test street"},
            {"email", "jon@mail.com"}
        };

        _controller.ValueProvider = formfakey;

        //execute
        var result = _controll开发者_Go百科er.ThemeContent(formfakey) as RedirectToRouteResult;

        // assert
        Assert.AreEqual("index", result.RouteValues["action"]);
        Assert.AreEqual("success", result.RouteValues["controller"]);

I had anticipated that I could essentially duplicate this code with a JSON object and set it to the controllers ValueProvider. This does not seem to be the case. Any assistance would be greatly appreciated.


Normally your controller action should take a strongly typed view model:

[HttpPost]
public ActionResult UpdateProduct(Product product)
{
    return View();
}

So you would test this controller action as any other controller actions. There's nothing special and related to JSON about this controller action:

[TestMethod]
public void SomeTest()
{
    // arrange
    var controller = new HomeController();
    var product = new Product();

    // act
    var actual = controller.UpdateProduct(product);

    // assert
    // TODO:
}

As you can see we never should mention any JSON about it. It's just the built-in JsonValueProviderFactory that allows interpreting binding JSON request to a .NET type but you don't need to test this. It is already built-in.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜