如何对HtmlHelper进行单元测试,类似于"using(Html.BeginForm()){}"; [英] How to Unit Test HtmlHelper similar to "using(Html.BeginForm()){ }"

查看:82
本文介绍了如何对HtmlHelper进行单元测试,类似于"using(Html.BeginForm()){}";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以建议我如何用Moq编写单元测试以遵循HtmlHelper方法吗?

Can somebody please suggest how I could write a Unit Test with Moq for following HtmlHelper method?

public static HtmlTagBase GenerateTag<T>(this HtmlHelper htmlHelper
                                   , object elementData
                                   , object attributes) 
    where T : HtmlTagBase
{
    return (T)Activator.CreateInstance(typeof(T)
                                       , htmlHelper.ViewContext
                                       , elementData
                                       , attributes);
}

,您将使用以下方法(请注意using语句-这引起了我的困惑):

which you would use as follows (please note the using statement - this is causing me confusion):

<%--Model is a type of ShareClass--%>
<% using (Html.GenerateTag<DivTag>(Model)) { %>
    My Div       
<% } %>

使用此方法,如果您将T指定为类型DivTag,其中ShareClass定义为

using this method, if you specify T as type DivTag, where ShareClass is defined as

public class ShareClass
{
    public string Name { get; set; }
    public string Type { get; set; }
    public IEnumerable<Fund> Funds { get; set; }

    public ShareClass(string name, string shareClassType)
    {
        this.Name = name;
        this.Type = shareClassType;
    }
}

将呈现以下html:

<div class="ShareClass" shareclass-type="ShareClass_A" shareclass-name="MyShareClass">My Div</div>

推荐答案

我认为这3个链接会有所帮助

I think this 3 links will help

  1. 准备HTML帮助器 https://stackoverflow.com/a/747186/980003
  2. 创建测试方法 https://stackoverflow.com/a/3424771/980003 (但请从第一个链接使用HtmlHelper )
  3. 按照您的期望保持结果正常.
  1. Prepare Html Helper https://stackoverflow.com/a/747186/980003
  2. Create test method https://stackoverflow.com/a/3424771/980003 (but use HtmlHelper from first link)
  3. Assert result with you expectations as normal.

这里是一次性帮手的例子.内部看起来如何. https://stackoverflow.com/a/8292524/980003

Here is example of disposable helper. How it looks like inside. https://stackoverflow.com/a/8292524/980003

这篇关于如何对HtmlHelper进行单元测试,类似于"using(Html.BeginForm()){}";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆