2010-10-15 70 views
8

我的目標是能夠單元測試一些自定義的HtmlHelper擴展 - 在內部使用RenderPartial。.net mvc2自定義HtmlHelper擴展單元測試

http://ox.no/posts/mocking-htmlhelper-in-asp-net-mvc-2-and-3-using-moq

我已經使用上述方法嘲笑的HtmlHelper試過。但是,我遇到了空值異常。 「參數名稱:視圖」

任何人有什麼想法?謝謝。

下面是代碼的思路:

[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

您需要發佈更多詳細信息,以便我們可以重現問題。我已經使用了前面提到的代碼(我寫它)來測試用'RenderPartial'呈現視圖沒有問題的控制器。 – 2010-10-18 20:39:12

回答

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);