【问题标题】:MVC Unit Test RadioButton Helper extensionMVC 单元测试 RadioButton Helper 扩展
【发布时间】:2011-09-06 02:23:09
【问题描述】:

在我的另一个问题中,我得到了一个非常好的帮助方法的答案:

using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class RadioExtensions
{ 
    public static IHtmlString MyRadioButtonFor<TModel, TProperty>(
        this HtmlHelper<TModel> html,
        Expression<Func<TModel, TProperty>> ex,
        object value
    )
    {
        var isAuthenticated = html.ViewContext.HttpContext.User.Identity.IsAuthenticated;
        if (isAuthenticated)
        {
            return html.RadioButtonFor(ex, value);
        }

        return html.RadioButtonFor(ex, value, new { @disabled = "disabled" });
    }
}

无论如何我正在尝试对此进行单元测试:

[Test]
        public void RadioButtonHelper()
        {
            var cc = new Mock<ControllerContext>(
                new Mock<HttpContextBase>(),
                new RouteData(),
                new Mock<ControllerBase>());

            var mockViewContext = new Mock<ViewContext>(
                cc,
                new Mock<IView>(),
                new TempDataDictionary());

            var mockViewDataContainer = new Mock<IViewDataContainer>();

            HtmlHelper helper = new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object);

            helper.
        }

当我到达调用方法的部分时,我无法到达该方法。

有人知道怎么做吗?

【问题讨论】:

  • 可能看起来很傻,但是您是否已将命名空间添加到您的测试类的扩展中?
  • 你不需要模拟任何东西。只要HtmlHelper helper = null; 就能得到你想要的东西

标签: asp.net-mvc unit-testing mocking html-helper


【解决方案1】:

尝试将命名空间作为using 包含在顶部。

【讨论】:

    【解决方案2】:

    要测试您的静态助手,只需执行以下操作

    [Test]
    public void MyHelperTests()
    {
      HtmlHelper html = null;
      var result = html.MyRadioButtonFor(/* your params */);
      Assert.IsInstanceOfType(typeof(MvcHtmlString), result);
      Assert.AreEqual(/* your results */, result.ToString());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 2013-05-08
      • 2019-08-18
      • 2020-07-12
      • 2012-11-14
      相关资源
      最近更新 更多