MVC Preview 5 - Rendering A View To String For Testing

烈酒焚心 提交于 2019-12-22 04:42:43

问题


I was reading a post by Brad Wilson (http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html) on the new ViewEngine changes to MVC Preview 5 and thought that it would be great to be able to render a view to string for use in tests. I get the impression from the article that it may be possible to achieve this but cannot figure out how.

I believe this would enable us to do away with some of our WatIn tests (which are slow and unreliable) as it would allow us to check that the View has rendered correctly by simply checking the string for expected values/text.

Has anyone implemented something like this?


回答1:


It's tricky. What you have to do is set the Response.Filter property to a custom stream class that you implement. The MVC Contrib project actually has examples of doing this. I'd poke around in there.




回答2:


I think here is what you need. The RenderPartialToString function will return the controller as a string. I get it from here.

public static string RenderPartialToString(string controlName, object viewData)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };
     Control control = vp.LoadControl(controlName);

     vp.Controls.Add(control);

     StringBuilder sb = new StringBuilder();
     using (StringWriter sw = new StringWriter(sb))
     {
         using (HtmlTextWriter tw = new HtmlTextWriter(sw))
         {
             vp.RenderControl(tw);
         }
     }

     return sb.ToString();
}



回答3:


Moreover testing, it can be useful for components such as HTML to PDF converters. These components usually uses 2 ways of transformation.

  • Passing a URL to the conversion method
  • Passing a HTML content (and you can optionally specify the baseUrl to resolve virtual paths)

I am using an Authorize filter inside the controller, so if I redirect to the URL the rendered HTML is the login page one (I use a custom authentication).

If I use Server.Execute(Url) to keep the context, the method fails (HttpUnhandledException: Error executing child request for /Template/Pdf/1.).

So I tried to retrieve the HTML of the rendered ViewResult but I didn't succeed.



来源:https://stackoverflow.com/questions/115060/mvc-preview-5-rendering-a-view-to-string-for-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!