单元测试ASP.net MVC中的HtmlHelper

时间:2016-07-13 08:51:00

标签: c# asp.net-mvc unit-testing mocking rhino-mocks

我有selected返回bootstrap public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string ccsClass = "selected") { var viewContext = html.ViewContext; var isChildAction = viewContext.Controller.ControllerContext.IsChildAction; if (isChildAction) { viewContext = html.ViewContext.ParentActionViewContext; } var routeValues = viewContext.RouteData.Values; var currentController = routeValues["controller"].ToString(); var currentAction = routeValues["action"].ToString(); if (string.IsNullOrEmpty(controllers)) { controllers = currentController; } if (string.IsNullOrEmpty(actions)) { actions = currentAction; } var acceptedActions = actions.Trim().Split(',').Distinct().ToArray(); var acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray(); return acceptedControllers.Contains(currentController) && acceptedActions.Contains(currentAction) ? ccsClass : string.Empty; } 类。我使用这个助手将活动状态应用到我的菜单项。

帮助代码

[Test]
public void WhenPassedControllerAndActionMatchContextReturnSelectedClass()
{
  var htmlHelper = CreateHtmlHelper(new ViewDataDictionary());
  var result = htmlHelper.IsSelected("performance", "search");

  Assert.AreEqual("selected", result);
}

public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData)
{
  var mocks = new MockRepository();

  var controllerContext = mocks.DynamicMock<ControllerContext>(
    mocks.DynamicMock<HttpContextBase>(),
    new RouteData(),
    mocks.DynamicMock<ControllerBase>());

  var viewContext = new ViewContext(controllerContext, mocks.StrictMock<IView>(), viewData, new TempDataDictionary(), mocks.StrictMock<TextWriter>());

  //var mockViewContext = MockRepository.GenerateMock<ViewContext>();

  var mockViewDataContainer = mocks.DynamicMock<IViewDataContainer>();

  mockViewDataContainer.Expect(v => v.ViewData).Return(viewData);

  return new HtmlHelper(viewContext, mockViewDataContainer);
}

测试代码

ControllerContext

这给了我一个错误。当我调试时,我发现这是因为null在帮助代码的第5行上是getActionBar().hide();

测试该代码的灵活,正确的方法是什么?

1 个答案:

答案 0 :(得分:1)

我注意到你正在使用rhino-mocks但是通过伪造HtmlHelper的依赖关系来使用Typemock Isolater解决问题是可能的(而且非常简单),如下例所示: / p>

[TestMethod, Isolated]
public void WhenPassedControllerAndActionMatchContextReturnSelectedClass()
{
    var fakeHtmlHalper = Isolate.Fake.Dependencies<HtmlHelper>();
    var fakeViewContext = Isolate.GetFake<ViewContext>(fakeHtmlHalper);

    Isolate.WhenCalled(() => fakeViewContext.RouteData.Values["controller"]).WillReturn("performance");
    Isolate.WhenCalled(() => fakeViewContext.RouteData.Values["action"]).WillReturn("search");

    var result = fakeHtmlHalper.IsSelected("performance", "search");

    Assert.AreEqual("selected", result);

}
相关问题