views:

47

answers:

2

Hi, I cannot seem to return the result.ViewName for use in Nunit tests as it always returns string.empty. I have explicitly set the name of the view inside my controller and would expect the test to pick this up. I have had a hunt around and it seems that I should get the Viewname back if I set it explicitly. Any one got any ideas?

public class HomeController : Controller
{

    public ActionResult Index()
    {
        return View("Index");
    }
}

My test looks like this

    [Test]
    public void TestIndexView()
    {
        var controller = new HomeController();
        var result = controller.Index() as ViewResult;
        Assert.AreEqual("Index", result.ViewName);
    }
A: 

You need to return new View("Index");. If this were C the reason why is because of the way you're creating the View in Index() it is just stored on the stack and goes out of scope (and thus gets collected) when the function ends. This would cause C to crash, but C# appears to be a little smarter in this regard.

Donnie
Really? According to http://www.asp.net/learn/mvc/tutorial-07-cs.aspx it does not mention "new"...
Rippo
View() function creates ViewResult.
LukLed
Ah, oops. I was thinking view was a class, not a function. Fail.
Donnie
@Donnie, No worries!
Rippo
+1  A: 

Did you try cleaning and rebuilding solution? It should work without problems.

LukLed