在ASP.NET MVC测试HtmlHelpers [英] Testing HtmlHelpers in ASP.NET MVC

查看:215
本文介绍了在ASP.NET MVC测试HtmlHelpers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法(单位)测试我自己HtmlHelpers?如果我想有自定义的控制(通过Htm​​lHelper的渲染),我知道该控件requierements我怎么能先写测试 - 然后写code?是否有一个具体的(NICE)的方式来做到这一点?

Is there any way to (unit) test my own HtmlHelpers? In case when I'd like to have custom control (rendered by HtmlHelper) and I know requierements for that control how could I write tests first - and then write code? Is there a specific (nice) way to do that?

是否值得?

推荐答案

主要的问题是,你有,因为你可能会使用辅助的方法来获取路线或值或返回的另一种扩展方法的结果,以嘲笑的HtmlHelper 。该HtmlHelper类有相当多的特性,其中一些相当复杂,如ViewContext或电流控制器。

The main problem is that you have to mock the HtmlHelper because you may be using methods of the helper to get routes or values or returning the result of another extension method. The HtmlHelper class has quite a lot of properties and some of them quite complex like the ViewContext or the current Controller.

<一个href="http://web.archive.org/web/20090615064637/http://blog.benhartonline.com/post/2008/10/17/Mocking-ASPNET-MVC-HtmlHelper-extension-methods-using-Moq.aspx">This从本·哈特说明如何创建起订量这样一个模拟发布。可以很容易地转换到另一个模拟框架。

This post from Ben Hart that explains how to create such a mock with Moq. Can be easily translated to another mock framework.

这是我的适应变化MVC框架犀牛制品的版本。这不是全面的测试,但它为我工作,但不要指望完美的结果:

This is my Rhino Mocks version adapted to the changes in the MVC Framework. It's not fully tested but it's working for me but don't expect perfect results:

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

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

        var mockViewContext = mocks.DynamicMock<ViewContext>(
            cc,
            mocks.DynamicMock<IView>(),
            viewData,
            new TempDataDictionary());

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

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

        return new HtmlHelper(mockViewContext, mockViewDataContainer);
    }

这篇关于在ASP.NET MVC测试HtmlHelpers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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