Is there any way to (unit) test my own HtmlHelpers? In case when I’d like to have custom control (rendered by HtmlHelper) and I know requierements for that control how could I write tests first – and then write code? Is there a specific (nice) way to do that?
Is it worth?
The main problem is that you have to mock the HtmlHelper because you may be using methods of the helper to get routes or values or returning the result of another extension method. The HtmlHelper class has quite a lot of properties and some of them quite complex like the ViewContext or the current Controller.
This post from Ben Hart that explains how to create such a mock with Moq. Can be easily translated to another mock framework.
This is my Rhino Mocks version adapted to the changes in the MVC Framework. It’s not fully tested but it’s working for me but don’t expect perfect results: