在测试情况下,我希望能够使用默认的viewEngine将给定的ViewResult呈现为HTML。
目前,我的视图是基于webforms的。但我可能会有Spark或Razor的观点。现在,我想关注WebForms。我可以从测试中呈现我的视图吗?
这里有一个方法可以让您将ViewResult呈现为字符串。在你的上下文中使用它的唯一棘手的部分是模拟一个可行的ControllerContext。
static string RenderPartialViewToString(ControllerContext context, ViewResultBase partialViewResult)
{
Require.ThatArgument(partialViewResult != null);
Require.That(context != null);
using (var sw = new StringWriter())
{
if (string.IsNullOrEmpty(partialViewResult.ViewName))
{
partialViewResult.ViewName = context.RouteData.GetRequiredString("action");
}
ViewEngineResult result = null;
if (partialViewResult.View == null)
{
result = partialViewResult.ViewEngineCollection.FindPartialView(context, partialViewResult.ViewName);
if(result.View == null)
throw new InvalidOperationException(
"Unable to find view. Searched in: " +
string.Join(",", result.SearchedLocations));
partialViewResult.View = result.View;
}
var view = partialViewResult.View;
var viewContext = new ViewContext(context, view, partialViewResult.ViewData,
partialViewResult.TempData, sw);
view.Render(viewContext, sw);
if (result != null)
{
result.ViewEngine.ReleaseView(context, view);
}
return sw.ToString();
}
}