MVC 3 - Unit Test Result of the controller

I am writing unit tests to test MVC 3 controllers. I want to make sure that the view that is returned from the controller is the correct view. In my unit test, I have:

[Test]
            public void It_Should_Return_The_Right_Page()
            {
                FormController fc = this.CreateFormController();
                var view = fc.FindX();
                Assert.AreEqual("FindX", view.ViewName);
            }

In my controller, I have:

public ViewResult FindX()
        {
            return View();
        }

This does not work because ViewName is null. If I change the call to say return View("FindX")and explicitly define the return view, it works. However, I would like to avoid this if possible. Is there a generally accepted way to approach this?

+3
source share
3 answers

If you do not specify a view name, it will not be a ViewName equal to zero, the correct and expected result, so copy your test accordingly.

Assert.IsNull(view.ViewName);
+2

, : , . - :

var view = fc.FindX();

Assert.IsNull(view.ViewName) 

. - ActionResult ViewResult AssertIsDefaultView :

public static class ActionResultAssertions
{
    public static void AssertIsDefaultView(this ActionResult actionResult)
    {
        var viewResult = actionResult as ViewResult;

        Assert.IsNotNull(viewResult);
        Assert.IsNull(viewResult.ViewName);
    }
}

:

var view = fc.FindX();
view.AssertIsDefaultView();

MvcContrib ( , - AssertViewRendered), , MVC.

+4

who worked for me

public ViewResult FindX()
    {
        return View("FindX");
    }
0
source

All Articles