The ViewDataDictionary that is passed to the HtmlHelper can be empty, or made to contain the data you want for your test.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd) | |
{ | |
var mockViewContext = new Mock( | |
new ControllerContext( | |
new Mock().Object, | |
new RouteData(), | |
new Mock().Object), | |
new Mock().Object, | |
vd, | |
new TempDataDictionary()); | |
var mockViewDataContainer = new Mock(); | |
mockViewDataContainer.Setup(v => v.ViewData) | |
.Returns(vd); | |
return new HtmlHelper(mockViewContext.Object, | |
mockViewDataContainer.Object); | |
} |
This code does not compile because the viewData variable on line 15 does not exist.
ReplyDeleteBut I'm presuming the "viewData" variable on line 15 was intended to be "vd".
ReplyDeleteThanks for spotting, updated now.
ReplyDeleteHi, I've been trying to use your code, but I am having some problems when HtmlHelper is instanciated.
ReplyDeleteI've detailed the problem here: http://stackoverflow.com/questions/3445770/missingmethodexception-thrown-when-trying-to-mock-htmlhelper-with-moq
apparently the ViewContext constructor's signature has changed, but even when supplying an updated Mock, I'm seeing a MissingMethodException being thrown.
Eric,
ReplyDeletecheck out a version for MVC 2 and 3 in this new post.
This helpful guide makes mocking HTML Helper much easier.
ReplyDelete