skaz
skaz

Reputation: 22640

MVC 3 - Unit Test Controller Result

I am writing unit tests to test MVC 3 controllers. I want to ensure that that the view that comes back from the controller is the right 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 fails because ViewName is null. If I change the call to say return View("FindX") and explicitly define the view to be returned, it works. However, I would like to avoid this if possible. Is there a generally accepted way to approach this?

Upvotes: 3

Views: 3887

Answers (3)

Wazzz
Wazzz

Reputation: 195

that worked for me

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

Upvotes: 0

Brian Geihsler
Brian Geihsler

Reputation: 2087

It sounds like what you want to convey is: Assert that the default view for this method was returned. One way to convey this is using this line:

var view = fc.FindX();

Assert.IsNull(view.ViewName) 

But this doesn't convey your intent very well. One way to convey it more clearly is to create an extension method on ActionResult or ViewResult called AssertIsDefaultView like so:

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

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

Then in your test you can say:

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

MvcContrib has a set of these assertions (I think the name of the method is AssertViewRendered), but I prefer to just write the extensions myself so I can understand MVC better.

Upvotes: 4

Xhalent
Xhalent

Reputation: 3954

If you don't set a viewname, then isn't ViewName being null the correct and expected outcome, so code your test accordingly.

Assert.IsNull(view.ViewName);

Upvotes: 2

Related Questions