The type initializer for 'System.Web.Mvc.ViewEngines' threw an exception

2.9k views Asked by At

I am trying to unit test a void method that have controllercontext parameter and some more to send email. Email template render partial view using view engine. I mocked controllercontext. So render view throw an exception because ControllerContext have null value.

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

There are 2 answers

0
Ashley Kilgour On

I dont think the error is with your code. I think it is with you test project does not have all the dependencies, in package mananger, with the test project set at the Default project intal

PM > Install-Package Microsoft.AspNet.WebPages

I forget to add this everytime I do test on a MVC project.

0
Ahmed Elbatt On

All you need is to install Microsoft.Asp.Net.WebPages in your test solution from the Nuget Package Manager and try to build your solution and then your unit tests will work properly.

enter image description here