如何进行单元测试调用扩展方法html.EditorFor [英] How to unit test an extension method that calls html.EditorFor

查看:341
本文介绍了如何进行单元测试调用扩展方法html.EditorFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个扣球,我创建了一个漂亮的HTML辅助扩展方法在我的看法使用,效果不错。它会让我的意见,以便更容易维护。

During a spike, I created a nifty html helper extension method for use in my views, it worked well. It will make my views so much easier to maintain.

现在我需要弄清楚如何进行单元测试。下面是我所试图做的要点:

Now I need to figure out how to unit test it. Here is the gist of what I am trying to do:

public static MvcHtmlString EditorOrDisplayForBasedOnConvolutedBusinessLogic<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
    if (ConvolutedBusinessLogic())
    {
        return html.EditorFor(expression);
    }
    else
    {
        return html.DisplayFor(expression);
    }
}

这两个EditorFor和DisplayFor本身的扩展方法。如何在我的单元测试,我可以断言,基于输入我的ConvolutedBusinessLogic,要么EditorFor或DisplayFor被称为合适?如果做不到这一点,我怎么能树立正确的存根/假货/嘲笑,这样调用EditorFor或DisplayFor不抛出一个NullReferenceException,然后我可以断言返回的内容是正确的?

Both EditorFor and DisplayFor are themselves extension methods. How in my unit tests, can I assert that based on the input for my ConvolutedBusinessLogic, that either EditorFor or DisplayFor are called as appropriate? Failing that, how can I set up the right stubs/fakes/mocks so that the call to EditorFor or DisplayFor dont throw a NullReferenceException and then I can assert the content returned is correct?

推荐答案

我的嘲笑下,不完全不够的。切换到使用假货建立了基于<一个href=\"http://offroad$c$cr.com/index.php/2011/08/unit-testing-asp-net-html-helpers-with-simple-fakes/\" rel=\"nofollow\">http://offroad$c$cr.com/index.php/2011/08/unit-testing-asp-net-html-helpers-with-simple-fakes/和它的所有工作。

My mocked context was not complete enough. Switched to using fakes built based on http://offroadcoder.com/index.php/2011/08/unit-testing-asp-net-html-helpers-with-simple-fakes/ and it all worked.

我仍然欢迎就如何嘲笑它,而不是采用全套假货的答案。

I'd still welcome an answer on how to mock it instead of using a full set of fakes.

这篇关于如何进行单元测试调用扩展方法html.EditorFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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