views:

55

answers:

1

In my unit tests, I find that when I return from a controller action using View() with no view name, ViewResult.ViewName is set to string.Empty. In order for this to be set, it has to be specified as a parameter to the View() call. For example, given the following unit test:

[TextFixture]
public class MyControllerTests 
{
    [Test]
    public void TestMyAction() 
    {
        var controller = new MyController();
        var result = controller.MyAction();

        Assert.AreEqual("MyAction", result.ViewName);
    }
}

The following action implementation will cause the unit test to fail:

public class MyController : Controller 
{
    public ActionResult MyAction() 
    {
        return View();
    }
}

whilst this one will pass:

public class MyController : Controller 
{
    public ActionResult MyAction() 
    {
        return View("MyAction");
    }
}

I'm using ASP.NET MVC 2 (pre-beta) on .NET 4.0. I'm not using anything .NET 4.0-specific, however. I find this behaviour odd because I had thought that the ViewName was one of the reliable properties that could be checked in the unit tests' assertions.

+3  A: 

This is a well known "feature" of ASP.NET MVC. Microsoft has documented it since the first version...

When no explicit view name is specified, the framework is trying to find one based on conventions (in "Views\controllername\actionname" or "Shared\controllername\actionname"). ViewName is only relevant if you want to deviate from that convention. So your unit test makes false assumptions.

HTH.

Thomas Weller
I see. Is there a recommended article/post/whatever on the appropriate assertions to make?
alastairs
Not a single one. If you google for something like "asp.net mvc unit testing", you get hundreds of articles/blog posts that deal with this issue.It totally depends on what exactly you want to test.
Thomas Weller