MVC3 Тестирование действия Create и возвращение созданного объекта - TempData? - PullRequest
1 голос
/ 14 октября 2011

Как передать успешно созданный объект из действия Create с помощью RedirectToAction?

Все выглядит хорошо в действии, просто не может ссылаться на него в тесте.

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

иметод действия:

  [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);
        }
    }
...