2017-01-03 80 views
1

我想單元測試一個具有controllercontext參數的無效方法以及一些發送電子郵件的方法。電子郵件模板使用視圖引擎渲染部分視圖我嘲笑controllercontext。所以渲染視圖拋出一個異常,因爲ControllerContext具有空值。'System.Web.Mvc.ViewEngines'的類型初始值設定項引發了一個異常

public static string RenderViewToString(ControllerContext context, string viewPath, object model, bool partial = false) 
     { 
      var viewEngineResult = partial ? ViewEngines.Engines.FindPartialView(context, viewPath) : ViewEngines.Engines.FindView(context, viewPath, null); 

      if (viewEngineResult == null) 
       throw new FileNotFoundException("View cannot be found."); 

      var view = viewEngineResult.View; 
      context.Controller.ViewData.Model = model; 

      var result = String.Empty; 

      using (var sw = new StringWriter()) 
      { 
       var ctx = new ViewContext(context, view, 
              context.Controller.ViewData, 
              context.Controller.TempData, 
              sw); 
       view.Render(ctx, sw); 
       result = sw.ToString(); 
      } 

      return result; 
     } 
+1

請張貼一些代碼 – NicoRiff

+1

沒有人可以幫助你,如果你不提供你的代碼。 – Sefe

+0

@NicoRiff有我的代碼 –

回答

1

我不認爲錯誤是與您的代碼。我認爲這是與你的測試項目沒有所有的依賴,在包mananger,與測試項目設置爲默認項目INTAL

PM>安裝,包裝Microsoft.AspNet.WebPages

我忘了每次我在一個MVC項目上進行測試時都會添加這個。

4

您只需要從Nuget Package Manager的測試解決方案中安裝Microsoft.Asp.Net.WebPages,然後嘗試構建解決方案,然後單元測試將正常工作。

enter image description here

相關問題