Gracie Omoplata
Gracie Omoplata

Reputation: 281

How to test ModelMetadata.FromLambdaExpression in MVC?

I have an extension method for a helper class in an MVC4 project:

public static class ExtensionMethods
{

    public static object Value<TModel, TProperty>(this Expression<Func<TModel, TProperty>> expression, ViewDataDictionary<TModel> viewData)
    {
        return ModelMetadata.FromLambdaExpression(expression, viewData).Model;
    }

}

This does something very simple in a manner that is anything but simple.

So, how can this best be unit tested? It would be preferable to avoid mocking static methods or using dependency injection, but I am open minded if these really are the only viable approaches in this case.

Is this just a flawed design that could be improved so as to be more amenable to unit testing?

Upvotes: 5

Views: 1867

Answers (1)

Gracie Omoplata
Gracie Omoplata

Reputation: 281

This is indeed a flawed design and is presumably common. The correct method signature requires the parameter order to be switched:

public static object Value<TModel, TProperty>(this ViewDataDictionary<TModel> viewData, Expression<Func<TModel, TProperty>> expression)
{
    return ModelMetadata.FromLambdaExpression(expression, viewData).Model;
}

This can then be called from unit tests:

Expression<Func<Model, string>> expression = (t => t.PropertyName);
ExtensionMethods.Value<Model, string>(viewData, expression));

Upvotes: 3

Related Questions