开发者

Unit Testing the UpdateModel method within MVC 3.0

Updated

I have recently modified a view to post to its controller a json object rather than a formcollection.

In order to get the unit test for this controller working we set the formvalue provider to a dictionary object to stop the UpdateModel method from throwing nre's.

The resulting unit test below however, simply does not feel like the right thing to be doing. Any insight into how to rework this would be greatly appreciated.

    [HttpPost]
    public ActionResult ThemeContent(content model)
    {
        if (ModelState.IsValid)
        {
            var content = _contentRepository.GetContent(model.id);
            if (content == null)
            {
                content = new content();
                UpdateModel(content);
                _contentRepository.Add(content);
                _contentRepository.Save();
            }
            else
            {
                UpdateModel(content);
                _contentRepository.Save();
            }

            return Json(new
            {
                redirectUrl = Url.Action("index", "success", new {id = content.id}),
                isRedirect = true
            });
        }

        string errorMessage = "{";

        foreach (var key in ModelState.Keys)
        {
            var error = ModelState[key].Errors.FirstOrDefault();
            if (error != null)
            {
                if (errorMessage != "{")
                {
                    errorMessage += ",";
                }
                errorMessage += (char) 34 + "#" + key + (char) 34 + ":" + (char) 34 + error.ErrorMessage + (char) 34;
            }
        }

        errorMessage += "}";

        return Json(new
        {
            Message = errorMessage,
            is开发者_Go百科Redirect = false
        });

    }

Thanks in advance.


You need to mock the controller context in your unit test if the controller action your are trying to test relies on it. I would strongly recommend you looking at the MVCContrib.TestHelper which would simplify the task of mocking this context and making your unit tests more elegant.


Updated, as we were incorrectly using the updatemodel method.

       //setup
        var fakeContent = new content
        {
            address1 = "123 test street"
        };

        _controller.Url = new UrlHelper(
            new RequestContext(
                _controller.HttpContext, new RouteData()
                ),
            new RouteCollection()
            );

        //execute
        var result = _controller.ThemeContent(fakeContent) as JsonResult();

        //assert
        Assert.AreEqual("123 test street", _content.address1);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜