开发者

MVC3 Testing a Create Action and passing back created object - TempData?

开发者 https://www.devze.com 2023-04-12 18:11 出处:网络
How to pass a successfully created object from Create action with a RedirectToAction? All looks good in the action, just can\'t reference it in the test.

How to pass a successfully created object from Create action with a RedirectToAction?

All looks good in the action, just can't reference it in the test.

  [Test]
    public void a_new_trick_should_be_saved_to_db_when_date_created_field_is_blank_and_set_to_now() {
        var controller = new TricksController();
        var formCollection = new FormCollection() {
                                                        { "Name", "test" },
                                                        { "Description", "test desc" },
                                                        { "Votes", "" },
                                                        { "VideoURL", "" },
                                      开发者_JS百科                  { "DateCreated", ""}
                                                  };
        //on success result is always null
        var result = controller.Create(formCollection) as ViewResult;

        //**this will never work as result is null when success
        var newlyCreatedThing = result.TempData["newlyCreatedThing"];

        //on fail result holds the errors list
        string errorMessage = "";
        if (result != null)
            errorMessage = result.TempData["Error"].ToString();
        Assert.IsEmpty(errorMessage);
    }

and action method:

  [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "Administrator")]
    public ActionResult Create(FormCollection collection)
    {
        var itemToCreate = _tricksTable.CreateFrom(collection);
        try
        {
            //validation enforced on model (as an override on Massive)
            var expandoNewlyCreatedTrick = _tricksTable.Insert(itemToCreate);

            //pass back newly created trick so that tests can make sure data is right
            TempData["newlyCreatedThing"] = expandoNewlyCreatedTrick;
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            TempData["Error"] = "There was an error adding the trick: "+ ex.Message;
            return View(itemToCreate);
        }
    }
0

精彩评论

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