How to unit test an extension method that calls ht

2019-05-18 05:45发布

问题:

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.