Why does this asp.net mvc unit test fail?

Posted by Brian McCord on Stack Overflow See other posts from Stack Overflow or by Brian McCord
Published on 2010-05-22T05:58:34Z Indexed on 2010/05/22 6:00 UTC
Read the original article Hit count: 217

Filed under:
|

I have this unit test:

    [TestMethod]
    public void Delete_Post_Passes_With_State_4()
    {
        //Arrange
        ViewResult result = stateController.Delete( 4 ) as ViewResult;
        var model = (State)result.ViewData.Model;

        //Act
        RedirectToRouteResult redirectResult = stateController.Delete( model ) as RedirectToRouteResult;

        var newresult = stateController.Delete( 4 ) as ViewResult;
        var newmodel = (State)newresult.ViewData.Model;

        //Assert
        Assert.AreEqual( redirectResult.RouteValues["action"], "Index" );
        Assert.IsNull( newmodel );
    }

Here are the two controller actions that handle deleting:

    //
    // GET: /State/Delete/5

    public ActionResult Delete(int id)
    {
        var x = _stateService.GetById( id );
        return View(x);
    }

    //
    // POST: /State/Delete/5

    [HttpPost]
    public ActionResult Delete(State model)
    {
        try
        {
            if( model == null )
            {
                return View( model );
            }

            _stateService.Delete( model );

            return RedirectToAction("Index");
        }
        catch
        {
            return View( model );
        }
    }

What I can't figure out is why this test fails. I have verified that the record actually gets deleted from the list. If I set a break point in the Delete method on the line:

var x = _stateService.GetById( id );

The GetById does indeed return a null just as it should, but when it gets back to the newresult variable in the test, the ViewData.Model is the deleted model.

What am I doing wrong?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about unit-testing