Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to unit test a method that converts a razor (cshtml) view to a string and returns it.
I tried to mock the HttpContext but was not very successful.

here is the method:
C#
public static string RenderViewToString(string viewPath,object model = null)
{
	var context = new ControllerContext(HttpContext.Current.Request.RequestContext, new MyController());
	// first find the ViewEngine for this view
	ViewEngineResult viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
	
	var view = viewEngineResult.View;
	context.Controller.ViewData.Model = model;

	string result = null;

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


What I have tried:

This method works fine when executed but I have trouble to unit test it as the context.Route value comes empty.

Any suggestions?
Posted
Updated 24-Mar-21 5:41am
v2

1 solution

You won't be able to test that method, since it's using HttpContext.Current.

You should change the method so that you pass in an HttpContextBase instance - or preferably a RequestContext instance - as a parameter.
C#
public static string RenderViewToString(RequestContext requestContext, string viewPath, object model = null)
{
    var context = new ControllerContext(requestContext, new MyController());
    ...
Code that calls it from within a controller can pass in the controller's ControllerContext.RequestContext instance.

Code that calls it from a static method can pass in HttpContext.Current.Request.RequestContext, or be modified to accept the RequestContext as a parameter.

Your unit test code then only needs to mock the RequestContext object.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900