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:
public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData)
{
var mocks = new MockRepository();
var cc = mocks.DynamicMock<ControllerContext>(
mocks.DynamicMock<HttpContextBase>(),
new RouteData(),
mocks.DynamicMock<ControllerBase>());
var mockViewContext = mocks.DynamicMock<ViewContext>(
cc,
mocks.DynamicMock<IView>(),
viewData,
new TempDataDictionary());
var mockViewDataContainer = mocks.DynamicMock<IViewDataContainer>();
mockViewDataContainer.Expect(v => v.ViewData).Return(viewData);
return new HtmlHelper(mockViewContext, mockViewDataContainer);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…