开发者

How to unit test this simple ASP.NET MVC controller

开发者 https://www.devze.com 2022-12-28 08:49 出处:网络
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).

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 witho开发者_JAVA百科ut 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>


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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号