在 ASP.net MVC 中对 HtmlHelper 进行单元测试

本文关键字:单元测试 HtmlHelper 中对 ASP net MVC | 更新日期: 2023-09-27 17:56:47

我有一个返回引导selectedHtmlHelper。我使用此帮助程序将活动状态应用于我的菜单项。

帮助程序代码

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在帮助程序代码的第 5 行null

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

在 ASP.net MVC 中对 HtmlHelper 进行单元测试

我注意到您正在使用 rhino-mock,但是可以通过伪造 HtmlHelper 的依赖项来使用 Typemock Isolater 解决您的问题,如以下示例所示:

[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);
}