Asp.net mvc MVC单元测试RadioButton辅助扩展
在我的另一个问题中,我得到了一个非常好的答案作为帮助方法:Asp.net mvc MVC单元测试RadioButton辅助扩展,asp.net-mvc,unit-testing,mocking,html-helper,Asp.net Mvc,Unit Testing,Mocking,Html Helper,在我的另一个问题中,我得到了一个非常好的答案作为帮助方法: 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&
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" });
}
}
使用系统;
使用System.Linq.Expressions;
使用System.Web;
使用System.Web.Mvc;
使用System.Web.Mvc.Html;
公共静态类无线电扩展
{
公共静态IHtmlString MyRadioButton(
这个HtmlHelper html,
表达式ex,
对象值
)
{
var isAuthenticated=html.ViewContext.HttpContext.User.Identity.isAuthenticated;
如果(未经验证)
{
返回html.radioButton(ex,value);
}
返回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.
}
[测试]
public void RadioButtonHelper()
{
var cc=新模拟(
新的Mock(),
新路由数据(),
新Mock());
var mockViewContext=new Mock(
复写的副本,
新的Mock(),
新的TempDataDictionary());
var mockViewDataContainer=new Mock();
HtmlHelper=新的HtmlHelper(mockViewContext.Object,mockViewDataContainer.Object);
帮手。
}
当我到达调用方法的部分时,我无法到达该方法
有人知道怎么做吗?尝试使用顶部的将名称空间作为一个
包含到扩展中。要测试静态助手,只需执行以下操作
[Test]
public void MyHelperTests()
{
HtmlHelper html = null;
var result = html.MyRadioButtonFor(/* your params */);
Assert.IsInstanceOfType(typeof(MvcHtmlString), result);
Assert.AreEqual(/* your results */, result.ToString());
}
可能看起来很傻,但是您在测试类中将名称空间添加到扩展了吗?您不需要模拟任何东西。只是HtmlHelper helper=null
会帮你得到你想要的