views:

225

answers:

1

I want to test the data inside the "item" object before it redirect to another action.

     public ActionResult WebPageEdit(WebPage item, FormCollection form)
    {
        if (ModelState.IsValid)
        {

            item.Description = Utils.CrossSiteScriptingAttackCheck(item.Description);
            item.Content = Utils.CrossSiteScriptingAttackCheck(item.Content);
            item.Title = item.Title.Trim();
            item.DateUpdated = DateTime.Now;

           // Other logic stuff here

            webPagesRepository.Save(item);


            return RedirectToAction("WebPageList");
        }

Here is my Test method:

[Test]
    public void Admin_WebPageEdit_Save()
    {

        var controller = new AdminController();

        controller.webPagesRepository = DataMock.WebPageDataInit();
        controller.categoriesRepository = DataMock.WebPageCategoryDataInit();

        FormCollection form = DataMock.CreateWebPageFormCollection();


        RedirectToRouteResult actionResult = (RedirectToRouteResult)controller.WebPageEdit(webPagesRepository.Get(1), form);
        Assert.IsNotNull(actionResult);

        Assert.AreEqual("WebPageList", actionResult.RouteValues["action"]);


        var item = ((ViewResult)controller.WebPageEdit(webPagesRepository.Get(1), form)).ViewData.Model as WebPage;

        Assert.NotNull(item);



        Assert.AreEqual(2, item.CategoryID);




    }

It failed at this line:

var item = ((ViewResult)controller.WebPageEdit(webPagesRepository.Get(1), form)).ViewData.Model as WebPage;

I am thinking about is there any ways to test the "item" object before it redirect to other actions?

A: 

The reason it failed, as you probably know, is that your controller action never returns a ViewResult, only a RedirectToRouteResult (assuming you haven't ellided some code path). You may return a ViewResult in the action you're redirecting to, but you are not testing that action here.

The best way to ascertain and test the state of your item object prior to redirection is its interaction with the Save() method of your webPagesRepository object. Presumably, from the name of test method, you want to test that this method is actually being called anyway. Therefore you should have an expectation on the Save() method. Within that expectation you can then examine and assert the state of the item object that is passed to it. This assumes that your webPagesRepository is a mocked dependency.

I'm a Rhino Mocks user and so only know how to set up the expectation using that API. Let me know if you'd find it useful nevertheless and I'll post it.

Andy Grout