我的目标是能够对一些自定义HtmlHelper扩展进行单元测试 - 这些扩展在内部使用RenderPartial。
http://ox.no/posts/mocking-htmlhelper-in-asp-net-mvc-2-and-3-using-moq
我尝试使用上面的方法来模拟HtmlHelper。但是,我遇到了Null值异常。 “参数名称:视图”
任何人都有任何想法?感谢。
以下是代码的想法:
[TestMethod]
public void TestMethod1()
{
var helper = CreateHtmlHelper(new ViewDataDictionary());
helper.RenderPartial("Test"); // supposingly this line is within a method to be tested
Assert.AreEqual("test", helper.ViewContext.Writer.ToString());
}
public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd)
{
Mock<ViewContext> mockViewContext = new Mock<ViewContext>(
new ControllerContext(
new Mock<HttpContextBase>().Object,
new RouteData(),
new Mock<ControllerBase>().Object),
new Mock<IView>().Object,
vd,
new TempDataDictionary(),
new StringWriter());
var mockViewDataContainer = new Mock<IViewDataContainer>();
mockViewDataContainer.Setup(v => v.ViewData)
.Returns(vd);
return new HtmlHelper(mockViewContext.Object,
mockViewDataContainer.Object);
}
答案 0 :(得分:3)
检查一下......这是一篇很棒的文章http://blogs.teamb.com/craigstuntz/2010/09/10/38638/
答案 1 :(得分:2)
我遇到了同样的问题。当我将参数传递给新的Mock()时,它没有正确设置它们。您需要明确地设置它们:
mockViewContext.Setup(v => v.View).Returns(new Mock<IView>().Object);
mockViewContext.Setup(v => v.ViewData).Returns(viewData);
mockViewContext.Setup(v => v.TempData).Returns(new TempDataDictionary());
mockViewContext.Setup(v => v.Writer).Returns(writer);