How to unit test an extension method that calls html.EditorFor

梦想与她 提交于 2019-12-12 09:49:54

问题


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);
    }
}

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?


回答1:


My mocked context was not complete enough. Switched to using fakes built based on http://offroadcoder.com/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.



来源:https://stackoverflow.com/questions/9073103/how-to-unit-test-an-extension-method-that-calls-html-editorfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!