Skip to content Skip to sidebar Skip to footer

Unit Testing Generic Htmlhelper Methods With Nunit

I'm new to nUnit and I've been tasked with creating unit tests for some htmlhelper extension methods. How should I go about creating a unit test for the following method? publ

Solution 1:

Below is how you write a Unit Test for this. Note that since you have not specified that you use a Mock object framework I'm going to the poor man technique, which is the hand written stubs and mocks. There is also another helper method if you are using Moq.

It is important to note that, in order to simplify the code execution I have made couple of changes to your extension method, so the test would not fail unexpectedly. Checking for any unexpected behaver is a good defensive programming practice anyway.

Back to the tests.

SUT (System Under Test)

This is how the SUT (System Under Test) looks like and supporting types looks like. (Please feel free to modify to your need accordingly)

publicstaticclassMyHtmlHelper
{
    publicstatic MvcHtmlString EnumDropDownListForOrderBy<TModel, TEnum>
         (this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TEnum>> expression,
        bool orderById, string firstElement = null, object htmlAttributes = null, 
        Func<ModelMetadata> fromLambFunc = null)
    {
        ModelMetadata metadata =
        ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);    
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

        IEnumerable<SelectListItem> items = 
            values.Select(value => new SelectListItem()
        {
            Text = GetText(value),
            Value = value.ToString(),
            Selected = value.Equals(metadata.Model)
        });

        IEnumerable<SelectListItem> itemsFiltered = 
        items.Where(e => !string.IsNullOrEmpty(e.Text)).AsEnumerable();
        itemsFiltered = itemsFiltered.OrderBy(e => (orderById ? e.Text : e.Value));

        return htmlHelper.DropDownListFor
        (expression, itemsFiltered, firstElement, htmlAttributes);
    }

    privatestatic Type GetNonNullableModelType(ModelMetadata metadata) {
        returntypeof (SomeEnum);
    }

    privatestaticstringGetText<TEnum>(TEnum value) {
        returnvalue.GetAttributeFrom<DescriptionAttribute>(value.ToString()) != null
            ? value.GetAttributeFrom<DescriptionAttribute>(value.ToString()).Description
            : string.Empty;
    }
}

publicstaticclassExtensionMethodsAttr
{
    publicstatic T GetAttributeFrom<T>(thisobject instance, string propertyName) 
      where T : Attribute
    {
        var attrType = typeof(T);
        var property = instance.GetType().GetProperty(propertyName);

        return property != null ?
        (T)property.GetCustomAttributes(attrType, false).First() : default(T) ;
    }
}

publicenum SomeEnum { A,}

Unit Tests

[TestFixture]
publicclassHtmlHelperTests
{
    [Test]
    publicvoidEnumDropDownListForOrderBy_InvokeDropDownListFor_ReturnsExpectedSelectItemResult()
    {
        //Arrangevarexpected="<select id=\"Foo\" name=\"Foo\"></select>";
        varfakeHtmlHelper= CreateHtmlHelperStaticStubs
        (newViewDataDictionary(newFakeViewModel() {Foo = SomeEnum.A}));
        //var fakeHtmlHelper = CreateHtmlHelperUsingMoq
        (newViewDataDictionary(newFakeViewModel(){Foo = SomeEnum.A}));

        //Actvarresult= fakeHtmlHelper.EnumDropDownListForOrderBy
        (model => model.Foo, It.IsAny<bool>(), null, null, null);

        //Assert
        Assert.AreEqual(expected, result.ToString());
    }


    privatestatic HtmlHelper<FakeViewModel> 
         CreateHtmlHelperStaticStubs(ViewDataDictionary viewData)
    {
        varstubControllerContext=newControllerContext(newFakeHttpContext(), newRouteData(), newFakeController());

        varstubViewContext=newViewContext(stubControllerContext, newFakeView(),
            newViewDataDictionary(newFakeViewModel() { Foo = SomeEnum.A }),
            newTempDataDictionary(), newTextMessageWriter());

        varfakeViewDataContainer=newFakeViewDataContainer();
        fakeViewDataContainer.ViewData = viewData;

        returnnewHtmlHelper<FakeViewModel>(stubViewContext, fakeViewDataContainer);
    }

    //Moq versionprivatestatic HtmlHelper<FakeViewModel> 
       CreateHtmlHelperUsingMoq(ViewDataDictionary viewData)
    {
        varstubControllerContext=newMock<ControllerContext>();
        stubControllerContext.Setup(x => x.HttpContext).Returns(newMock<HttpContextBase>().Object);
        stubControllerContext.Setup(x => x.RouteData).Returns(newRouteData());
        stubControllerContext.Setup(x => x.Controller).Returns(newMock<ControllerBase>().Object); ;

        varstubViewContext=newMock<ViewContext>();
        stubViewContext.Setup(x => x.View).Returns(newMock<IView>().Object);
        stubViewContext.Setup(x => x.ViewData).Returns(viewData);
        stubViewContext.Setup(x => x.TempData).Returns(newTempDataDictionary());

        varmockViewDataContainer=newMock<IViewDataContainer>();

        mockViewDataContainer.Setup(v => v.ViewData).Returns(viewData);

        returnnewHtmlHelper<FakeViewModel>(stubViewContext.Object, mockViewDataContainer.Object);
    }
}   


classFakeHttpContext : HttpContextBase
{
    private Dictionary<object, object> _items = newDictionary<object, object>();
    public override IDictionary Items { get { return _items; } }
}

classFakeViewDataContainer : IViewDataContainer
{
    privateViewDataDictionary_viewData=newViewDataDictionary();
    public ViewDataDictionary ViewData { get { return _viewData; } set { _viewData = value; } }
}

classFakeController : Controller { }

classFakeView : IView
{
    publicvoidRender(ViewContext viewContext, System.IO.TextWriter writer)
    {
        thrownewNotImplementedException();
    }
}

publicclassFakeViewModel {
    public SomeEnum Foo { get; set; }
}

Post a Comment for "Unit Testing Generic Htmlhelper Methods With Nunit"