tags:

views:

101

answers:

1

Lets say I have a simple controller for ASP.NET MVC I want to test. I want to test that a controller action (Foo, in this case) simply returns a link to another action (Bar, in this case).

How would you test TestController.Foo? (either the first or second link)

My implementation has the same link twice. One passes the url throw ViewData[]. This seems more testable to me, as I can check the ViewData collection returned from Foo(). Even this way though, I don't know how to validate the url itself without making dependencies on routing.

The controller:

public class TestController : Controller
{
    public ActionResult Foo()
    {
        ViewData["Link2"] = Url.Action("Bar");
        return View("Foo");
    }

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

}

the "Foo" view:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" MasterPageFile="~/Views/Shared/Site.Master"%>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <%= Html.ActionLink("link 1", "Bar") %>

    <a href="<%= ViewData["Link2"]%>">link 2</a>
</asp:Content>
+1  A: 

The Foo method is actually less-easily testable because it uses the .Url property (of type UrlHelper) from the TestController's base class which is not pre-filled. If you want to go down the path of stubbing the UrlHelper object, then the following post describes how to go about this - ASP.NET MVC: Unit testing controllers that use UrlHelper.

The Bar method on the other hand, is more-easily testable as it doesn't use the Controller.Url property:

[TestMethod]
public void BarRouteReturnsBarViewResult()
{
    // Arrange
    var controller = new TestController();

    // Act
    var result = controller.Bar() as ViewResult;

    // Assert
    Assert.AreEqual(result.ViewName, "Bar");
}
Bermo
Thanks. I'll clarify my question though as Foo was what I was interested in. The answer in the linked question is pretty heavy, I was surprised it takes so much to test it and was hoping there was a quicker approach.
Frank Schwieterman