Hi all,
I have a problem with the following code.. I am trying write unit test the view pages of MV... My code is executing without an error but it returns null value when call the RenderView method... Can any one please help me with this ? My code is as follows.
private static string RenderView(string controllerName, string viewName, string queryString, object viewData)
{
StringBuilder result = new StringBuilder();
string virtualPath = string.Format("/{0}/{1}", controllerName, viewName);
HttpContextWrapper context = CreateHttpContext(result, virtualPath, queryString);
ControllerContext controllerContext = CreateControllerContext(context, controllerName, viewName);
ViewContext viewContext = new ViewContext(controllerContext, new Mock<IView>().Object, new ViewDataDictionary(viewData), new TempDataDictionary());
ViewEngineResult vrs = CreateView(viewName, viewData, controllerContext);
//vrs.View.Render(viewContext, new StringWriter(result));
//viewContext.View.Render(viewContext, new StringWriter(result));
context.Response.Flush();
return result.ToString();
}
private static HttpContextWrapper CreateHttpContext(StringBuilder result, string virtualPath, string queryString)
{
SimpleWorkerRequest wr = new SimpleWorkerRequest(virtualPath, queryString, new StringWriter(result));
HttpContext.Current = new HttpContext(wr);
return new HttpContextWrapper(HttpContext.Current);
}
private static ControllerContext CreateControllerContext(HttpContextWrapper context, string controllerName, string actionName)
{
RouteTable.Routes.Clear();
RouteTable.Routes.Add(new Route("{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { action = "Index", id = "" })
});
RouteData routeData = new RouteData();
routeData.Values.Add("controller", controllerName);
routeData.Values.Add("action", actionName);
MockRepository mocks = new MockRepository();
return new ControllerContext(context, routeData, mocks.DynamicMock<ControllerBase>());
}
private static ViewEngineResult CreateView(string viewName, object viewData, ControllerContext controllerContext)
{
CreateViewCL viewFactory = new CreateViewCL();
return viewFactory.FindView(controllerContext, viewName, "Site.Master");
}
Thanks in advance.